如何将数据框中的特定列与同一数据框中的一个特定列相乘?
How to multiply specific column from dataframe with one specific column in same dataframe?
我有一个数据框,我需要根据其他列与特定列的乘积来创建新列
这是我的数据框的样子。
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
我想将 Value 和 Factor 列与 Price 相乘以获得新列。我可以手动完成,但我有很多列,所有列都以特定前缀开头,我需要乘以...在这里我使用 S_
这意味着我需要乘以所有以 [=12= 开头的列]
这是所需的输出列
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
相乘来创建新列
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
因为您没有添加输出示例。这可能是您正在寻找的:
dfr = pd.DataFrame({
'Brand' : ['A', 'B', 'C', 'D', 'E', 'F'],
'price' : [10, 20, 30, 40, 50, 10],
'S_Value' : [2,4,2,1,1,1],
'S_Factor' : [2,1,1,2,1,1]
})
pre_fixes = ['S_']
for prefix in pre_fixes:
coltocal = [col for col in dfr.columns if col.startswith(prefix)]
for col in coltocal:
dfr.loc[:,col+'_new'] = dfr.price*dfr[col]
dfr
Brand price S_Value S_Factor S_Value_new S_Factor_new
0 A 10 2 2 20 20
1 B 20 4 1 80 20
2 C 30 2 1 60 30
3 D 40 1 2 40 80
4 E 50 1 1 50 50
5 F 10 1 1 10 10
只需添加尽可能多的前缀即可 pre_fixes
(使用 come 分隔它们)
我有一个数据框,我需要根据其他列与特定列的乘积来创建新列
这是我的数据框的样子。
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
我想将 Value 和 Factor 列与 Price 相乘以获得新列。我可以手动完成,但我有很多列,所有列都以特定前缀开头,我需要乘以...在这里我使用 S_
这意味着我需要乘以所有以 [=12= 开头的列]
这是所需的输出列
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
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
因为您没有添加输出示例。这可能是您正在寻找的:
dfr = pd.DataFrame({
'Brand' : ['A', 'B', 'C', 'D', 'E', 'F'],
'price' : [10, 20, 30, 40, 50, 10],
'S_Value' : [2,4,2,1,1,1],
'S_Factor' : [2,1,1,2,1,1]
})
pre_fixes = ['S_']
for prefix in pre_fixes:
coltocal = [col for col in dfr.columns if col.startswith(prefix)]
for col in coltocal:
dfr.loc[:,col+'_new'] = dfr.price*dfr[col]
dfr
Brand price S_Value S_Factor S_Value_new S_Factor_new
0 A 10 2 2 20 20
1 B 20 4 1 80 20
2 C 30 2 1 60 30
3 D 40 1 2 40 80
4 E 50 1 1 50 50
5 F 10 1 1 10 10
只需添加尽可能多的前缀即可 pre_fixes
(使用 come 分隔它们)