根据按ID分组的类别计算列中的值差异

时间:2019-04-10 16:36:44

标签: python pandas dataframe

我想通过存储在每个ID组的另一列中的状态来计算值的差异。

数据集为:

# Create the dataframe
d = {'ID': ['1', '1', '1', '1', '2', '2', '2', '2'], 
     'Category': ['A','B','C','D','A','B','C','D'],
     'Value': ['5','9','10','11','8','13','20','25']} 
df = pd.DataFrame(data=d)

数据集如下:

ID Category Value
1    A        5
1    B        9
1    C        10
1    D        11
2    A        8
2    B        13
2    C        20
2    D        25

例如,我想为每个ID计算类别B和D的值的差异。但是我不确定如何将计算与groupby相结合。

理想的数据集如下:

ID   diff(B,D)
1    2
2    12

感谢任何人回答这个问题!

3 个答案:

答案 0 :(得分:1)

使用groupby过滤后,您可以使用diffisin

df.Value=pd.to_numeric(df.Value)

yourdf=df.loc[df['Category'].isin(['B','D'])].set_index('ID').groupby(level=0)['Value'].diff().dropna()
yourdf
Out[75]: 
ID
1     2.0
2    12.0
Name: Value, dtype: float64

答案 1 :(得分:0)

另一种解决方法是使用MultiIndex

df2 = df.set_index(['ID', 'Category']).unstack(-1).xs('Value', axis=1, drop_level=True)

Category  A   B   C   D
ID                     
1         5   9  10  11
2         8  13  20  25

df2 = df2.apply(pd.to_numeric)
df2['D'] - df2['B']

ID
1     2
2    12
dtype: int64

答案 2 :(得分:-1)

您还可以尝试使用pivot_table,然后尝试以下差异的传统公式:

d = {'ID': ['1', '1', '1', '1', '2', '2', '2', '2'], 
     'Category': ['A','B','C','D','A','B','C','D'],
     'Value': ['5','9','10','11','8','13','20','25']} 
df = pd.DataFrame(data=d)
df.Value=pd.to_numeric(df.Value)
aa = df['Category'].unique()

# using a pivot table function to define in the column and then calculating the difference
df = df.pivot_table(index=['ID'],columns='Category',values='Value')
df['diff'] = df['D'] - df['B']
df = df.drop(columns=aa,axis=0)


output:
Category    diff
ID  
1           2
2           12

请告诉我它是否对您有用。

相关问题