如何基于熊猫数据框中的其他值从列中减去值

时间:2020-09-20 12:36:04

标签: python pandas dataframe

我有以下数据框:

import pandas as pd
data = [['tom', 10,2,'c',6], ['tom',16 ,3,'a',8], ['tom', 22,2,'a',10],['matt', 10,1,'c',11]]

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Col a','Col c','Category', 'Value']) 
df

enter image description here

如何设置一个名为Calculation的新列,其中取决于Category的计算将使用哪一列?

例如,如果Category=='a',那么我希望计算为df['Value'] - df['Col a']

我的预期输出应该是:

    Name    Col a   Col c   Category    Value   Calculation
0   tom      10       2          c      6            4
1   tom      16       3          a      8           -8
2   tom      22       2          a      10          -12
3   matt     10       1          c      11           10

我有很多不同的列,所以(也许有10种可能的计算很高兴将它们硬编码到其中)

对此将提供任何帮助!

1 个答案:

答案 0 :(得分:3)

您可以使用DataFrame.lookup根据相应的类别从列中获取值,然后从列Value中减去它们:

df['Calc'] = df['Value'] - df.lookup(df.index, df['Category'].radd('Col '))

   Name  Col a  Col c Category  Value  Calc
0   tom     10      2        c      6     4
1   tom     16      3        a      8    -8
2   tom     22      2        a     10   -12
3  matt     10      1        c     11    10