Python 在列上应用 sqrt 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37256540/
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-19 19:08:04 来源:igfitidea点击:
Applying sqrt function on a column
提问by Night Walker
I have following data frame
我有以下数据框
data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
'wins': [11, 8, 10, 15, 11, 6, 10, 4],
'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses'])
football.set_index(['team', 'year'], inplace=True)
How I can apply sqrt
function after I do sum to the columns?
sqrt
对列求和后如何应用函数?
football[['wins', 'losses']].sum(axis=1)
回答by Stefan
Just use numpy.sqrt()
(see docs) on the resulting pd.Series
:
只需在结果上使用numpy.sqrt()
(参见文档)pd.Series
:
import numpy as np
np.sqrt(football[['wins', 'losses']].sum(axis=1))
But there are of course several ways to accomplish the same result - see below for illustration:
但是当然有几种方法可以实现相同的结果 - 请参见下面的说明:
df = pd.DataFrame.from_dict(data={'col_1': np.random.randint(low=1, high=10, size=10), 'col_2': np.random.randint(low=1, high=10, size=10)}, orient='index').T
df['sum'] = df[['col_1', 'col_2']].sum(axis=1)
df['np'] = np.sqrt(df[['col_1', 'col_2']].sum(axis=1))
df['apply'] = df[['col_1', 'col_2']].sum(axis=1).apply(np.sqrt)
df['**'] = df[['col_1', 'col_2']].sum(axis=1) ** .5
col_1 col_2 sum np apply **
0 8 3 11 3.316625 3.316625 3.316625
1 4 1 5 2.236068 2.236068 2.236068
2 6 2 8 2.828427 2.828427 2.828427
3 4 1 5 2.236068 2.236068 2.236068
4 4 7 11 3.316625 3.316625 3.316625
5 7 4 11 3.316625 3.316625 3.316625
6 5 5 10 3.162278 3.162278 3.162278
7 1 2 3 1.732051 1.732051 1.732051
8 6 6 12 3.464102 3.464102 3.464102
9 5 7 12 3.464102 3.464102 3.464102