如何将数据框中的特定列与同一数据框中的一个特定列相乘? [英] How to multiply specific column from dataframe with one specific column in same dataframe?
问题描述
我有一个数据框,需要根据其他列与特定列的相乘来创建新列
I have a dataframe where i need to create new column based on the multiplication of other column with specific column
这是我的数据框的外观.
Here is how my data frame looks.
df:
Brand Price S_Value S_Factor
A 10 2 2
B 20 4 1
C 30 2 1
D 40 1 2
E 50 1 1
F 10 1 1
我想将值"和因子"乘以价格"来获得新的列.我可以手动完成,但是我有很多列,而且所有列都以特定的前缀开始,我需要相乘...在这里,我使用了 S _
,这意味着我需要将所有以<代码> S _
I would like multiply column Value and Factor with Price to get new column. I can do it manually but I have a lot of column and all start with specific prefix wihivh i need to multiply... here I used S_
which mean I need to multiply all the columns which start with S_
这将是所需的输出列
Brand Price S_Value S_Factor S_Value_New S_Factor_New
A 10 2 2
B 20 4 1
C 30 2 1
D 40 1 2
E 50 1 1
F 10 1 1
推荐答案
首先,要获取必须相乘的列,可以使用列表推导和字符串函数 startswith
.然后只需在列上循环并通过与 Price
Firstly, to get the columns which you have to multiply, you can use list comprehension and string function startswith
. And then just loop over the columns and create new columns by muptiplying with Price
multiply_cols = [col for col in df.columns if col.startswith('S_')]
for col in multiply_cols:
df[col+'_New'] = df[col] * df['Price']
df
这篇关于如何将数据框中的特定列与同一数据框中的一个特定列相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!