如何在数据帧上添加减除和乘列?

时间:2019-09-10 14:25:35

标签: python pandas dataframe operation

我希望你能帮助我。 我需要得到以下结果: 对于每一行中的项目,请创建Max(In / Out Util)-1Mbr列,其结果为:

  

df ['Max(In / Out Util)-1Mbr'] = [df ['Max(In / Out Util)'] / 100 * df ['Egress   Speed']] / [df ['Egress Speed']-(df ['Egress Speed'] / df ['Oper。Member   数'])] * 100

原始DataFrame

Site Name           Oper. Member Count  Egress Speed    Max(In/Out Util)
KB201_XXX71_SR7                     2       6000000             11,1527 
KB201_XXX71_SR7                     2           N/A                 N/A 
KN092_XXX71_SR7                     4       4000000             9,60783

FinalDataFrame

Site Name           Oper. Member Count  Egress Speed    Max(In/Out Util)    Max(In/Out Util)-1Mbr
KB201_XXX71_SR7                     2       6000000             11,1527                     22,3
KB201_XXX71_SR7                     2           N/A                 N/A                     N/A
KN092_XXX71_SR7                     4       4000000             9,60783                     12,8

2 个答案:

答案 0 :(得分:3)

您需要做的就是设置数学公式,以列名表示结果:

   df['col4'] = (df['col1']+df['col2'])/df['col3']

编辑:新请求的公式:

df['Max(In/Out Util)-1Mbr'] = [df['Max(In/Out Util)']/100*df['Egress Speed']] / [df['Egress Speed']-(df['Egress Speed']/df['Oper. Member Count'])]*100 

EDIT2:基于您的数字是用拉丁符号编码的事实(这是逗号用来表示小数点),您应该使用:

df = df.apply(lambda x: x.str.replace(',','.'))
df['Max(In/Out Util)-1Mbr'] = df['Max(In/Out Util)-1Mbr'].astype(int)
df['Egress Speed'] = df['Egress Speed'].astype(int)
df['Oper. Member Count'] = df['Oper. Member Count'].astype(int)

然后是您建议的公式:

df['Max(In/Out Util)-1Mbr'] = (df['Max(In/Out Util)']*df['Egress Speed']) / (df['Egress Speed'] - df['Egress Speed'] / df['Oper. Member Count'])

只需使用最终公式即可。

答案 1 :(得分:1)

只是:

df['col4']= (df['col1']+df['col2'])/df['col3']