python - 在列上应用 sqrt 函数

标签 python numpy pandas dataframe

我有以下数据框

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)

最佳答案

只需使用 numpy.sqrt() ( see docs ) 在结果 pd.Series 上:

import numpy as np
np.sqrt(football[['wins', 'losses']].sum(axis=1))

但是当然有几种方法可以实现相同的结果 - 请参见下面的说明:
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

关于python - 在列上应用 sqrt 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37256540/

相关文章:

python - 将 float 舍入为 n 位,忽略前导零并保留它们

python - 编写一个引用实例和类的python方法

python - 加快 Pandas 的分组差异

python - 对 Pandas 中包含数字和分隔符的字符串进行排序

python - Pandas 是否支持 yyyyQp 形式的季度日期(例如 2013Q2)?

python - 有效连接 DataFrame 索引的两个标签

python - 多边形面积计算不一致

python - 过滤 Numpy 数组中的负值,排除相等但符号相反的值

python-3.x - 如何在groupy组的第一个值之前获取值

python - 动态删除单词的一部分