python - Pandas DataFrame 将特定函数应用于每一列

标签 python pandas

我有以下数据框:

>>> import numpy as np
>>> import pandas as pd
>>> df=pd.DataFrame()
>>> df['Var1']=np.random.randint(0,100,10)    
>>> df['Var2']=np.random.randint(0,10,10)   
>>> df
   Var1  Var2
0    46     2
1    10     3
2    30     6
3    49     4
4    62     3
5    64     8
6    26     0
7    41     2
8     3     2
9    22     3
>>> 

我有以下系列,其中包含每列将乘以的乘法因子:

>>> MultFactors=pd.Series(index=['Var1','Var2'],data=np.random.randn(2))
>>> MultFactors
Var1    0.833691
Var2   -1.408577
dtype: float64
>>> 

返回与原始数据帧形状相同并包含每个值乘以适当的乘法因子的数据帧的最佳方法是什么。我可以用 for 循环来做到这一点,但我想知道更有效的方法是什么。

>>> for MultFactor in MultFactors.index:
...     df[MultFactor]=df[MultFactor]*MultFactors[MultFactor]
... 
>>> df
        Var1       Var2
0  38.349773  -2.817155
1   8.336907  -4.225732
2  25.010722  -8.451464
3  40.850845  -5.634310
4  51.688825  -4.225732
5  53.356206 -11.268619
6  21.675959  -0.000000
7  34.181319  -2.817155
8   2.501072  -2.817155
9  18.341196  -4.225732
>>> 

最佳答案

这不会得到同样的结果吗?

df = df * MultFactor

关于python - Pandas DataFrame 将特定函数应用于每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34420867/

相关文章:

python - 使用正则表达式替换重叠的子模式

python - 如何在python中插入图像

使用 SecretKeyFactory 生成 secret 时,Java 字节数组到字符串必须等于 python 字节数组字符串

python - 使用 Pandas 列出第二列的所有值和第一列的计数

python-3.x - 在Python中仅将一行更改为列

python - Pandas 中的列操作

python - 如何让 strftime 输出年度季度?

python - 加快多个 CSV 文件的加载速度

python - 合并两个排序列表时,为什么我会得到两个不同的输出 (Python)

python - 循环遍历列并调整值 pandas