Pandas 将特定列乘以行中的值

Pandas Multiply Specific Columns by Value In Row

我正在尝试将特定列的值添加到它们各自的行中。

例如:

          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

使用 mulaxis = 0 也可以通过 get_level_values

得到 index
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广播

df.values*df.index.get_level_values(1)[:,None]
Out[177]: Int64Index([[10, 0, 10], [0, 0, 0], [80, 80, 80]], dtype='int64')
pd.DataFrame(df.values*df.index.get_level_values(1)[:,None],index=df.index,columns=df.columns)
Out[181]: 
       X   Y   Z
A 10  10   0  10
B 50   0   0   0
C 80  80  80  80

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

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