Python Pandas 中每一列元素的平方
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20644536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:55:25 来源:igfitidea点击:
Square of each element of a column in pandas
提问by Pierpaolo
How can I square each element of a column/series of a DataFrame in pandas (and create another column to hold the result)?
如何在 Pandas 中对 DataFrame 的列/系列的每个元素进行平方(并创建另一列来保存结果)?
采纳答案by alko
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2],[3,4]], columns=list('ab'))
>>> df
a b
0 1 2
1 3 4
>>> df['c'] = df['b']**2
>>> df
a b c
0 1 2 4
1 3 4 16
回答by postelrich
Nothing wrong with the accepted answer, there is also:
接受的答案没有错,还有:
df = pd.DataFrame({'a': range(0,100)})
np.square(df)
np.power(df, 2)
Which is ever so slightly faster:
哪个稍微快一点:
In [11]: %timeit df ** 2
10000 loops, best of 3: 95.9 μs per loop
In [13]: %timeit np.square(df)
10000 loops, best of 3: 85 μs per loop
In [15]: %timeit np.power(df, 2)
10000 loops, best of 3: 85.6 μs per loop

