在列上应用sqrt函数 [英] Applying sqrt function on a column
本文介绍了在列上应用sqrt函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框
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)
求和后如何应用sqrt
函数?
football[['wins', 'losses']].sum(axis=1)
推荐答案
Just use numpy.sqrt()
(see docs) on the resulting 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
这篇关于在列上应用sqrt函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文