熊猫将特定列乘以行中的值

时间:2018-10-11 19:13:20

标签: python pandas multiplication

我试图在多个特定列的相应行中添加一个值。

例如:

          X         Y         Z
A 10      1         0         1        
B 50      0         0         0      
C 80      1         1         1

将成为:

              X         Y         Z
A 10        10         0         10        
B 50        0          0         0      
C 80        80         80        80

我遇到的问题是使用mul()时超时。我的真实数据集非常大。我尝试在我的真实代码中使用循环对其进行迭代,如下所示:

for i in range(1,df_final_small.shape[0]): 
    df_final_small.iloc[i].values[3:248] = df_final_small.iloc[i].values[3:248] * df_final_small.iloc[i].values[2]

应用于示例数据框时,看起来像这样:

for i in range(1,df_final_small.shape[0]): 
    df_final_small.iloc[i].values[1:4] = df_final_small.iloc[i].values[1:4] * df_final_small.iloc[i].values[0]

必须有一种更好的方法,我在弄清楚如何只将乘法转换为行中的某些列而不是整个行时遇到了问题。

编辑: 在这里进一步详细说明是我的df.head(5)。

id  gross   150413 Welcome Email    150413 Welcome Email Repeat Cust    151001 Welcome Email    151001 Welcome Email Repeat Cust    161116 eKomi    1702 Hot Leads Email    1702 Welcome Email - All Purchases  1804 Hot Leads  ... SILVER  GOLD    PLATINUM    Acquisition Direct Mail Conversion Direct Mail  Retention Direct Mail   Retention eMail cluster x   y
0   0033333 46.2    0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0 0.0 1.0 0.0 10  -0.230876   0.461990
1   0033331 2359.0  0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0 0.0 1.0 0.0 9   0.231935    -0.648713
2   0033332 117.0   0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0 0.0 1.0 0.0 5   -0.812921   -0.139403
3   0033334 89.0    0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0 0.0 1.0 0.0 5   -0.812921   -0.139403
4   0033335 1908.0  0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0 1.0 0.0 0.0 7   -0.974142   0.145032

2 个答案:

答案 0 :(得分:1)

只需指定要相乘的列即可。例子

df=pd.DataFrame({'A':10,'X':1,'Y':1,'Z':1},index=[1])
df.loc[:,['X', 'Y', 'Z']]=df.loc[:,['X', 'Y', 'Z']].values*df.iloc[:,0:1].values

如果要提供任意范围的列,请使用iloc

range_of_columns= range(10,5001)+range(5030,10001)
df.iloc[:,range_of_columns].values*df.iloc[:,0:1].values #multiplying the range of columns with the first column

答案 1 :(得分:0)

mulaxis = 0一起使用,也会得到index的{​​{1}}值

get_level_values

此外,当数据框变大时,您可以将其拆分并按块进行。

df.mul(df.index.get_level_values(1),axis=0)
Out[167]: 
       X   Y   Z
A 10  10   0  10
B 50   0   0   0
C 80  80  80  80

我还将推荐dfs = np.split(df, [2], axis=0) pd.concat([x.mul(x.index.get_level_values(1), axis=0) for x in dfs]) Out[174]: X Y Z A 10 10 0 10 B 50 0 0 0 C 80 80 80 80 广播

numpy