在熊猫数据框上迭代数学函数

时间:2019-07-01 01:51:23

标签: python pandas dataframe iteration calculation

我正在尝试对数据框进行计算。 datarframe有65列。

id_1 Id_2   sum_id1 Sum_id2 Price   Cal_1   Cal_2
1    5      15      35      2       -68     -60
2    6      15      35      3       -99     -87
3    7      15      35      4       -128    -112
4    8      15      35      5       -155    -135
5    9      15      35      6       -180    -156

给出了从ID_1到价格的列。计算方式为(ID_1-SumID_1)*价格。我必须对此进行60列的迭代。所以我需要一个迭代的解决方案。

我已经尝试了Numpy的方法,但是它对于一次计算很有用。我必须遍历60多个列。

2 个答案:

答案 0 :(得分:2)

使用字符串替换的for循环怎么样?

# assuming there are 60 unique values
n = 60
for i in range(1, n+1):
    df[f'Cal_{i}'] = (df[f'Id_{i}'] - df[f'SumID_{i}']) * df['Price']

答案 1 :(得分:1)

我正在使用filter并重新创建数据框,然后concat将其返回

s=(df.filter(like='Id').values-df.filter(like='Sum').values)*df.Price.values[:,None]
s=pd.DataFrame(s,columns=['Cal_'+str(x+1) for x in range(s.shape[1])],index=df.index)
df=pd.concat([df,s],axis=1)
df
   Id_1  Id_2  sum_id1  Sum_id2  Price  Cal_1  Cal_2
0     1     5       15       35      2    -68    -60
1     2     6       15       35      3    -99    -87
2     3     7       15       35      4   -128   -112
3     4     8       15       35      5   -155   -135
4     5     9       15       35      6   -180   -156