Python Pandas:条件减法

时间:2017-07-18 16:30:24

标签: python pandas dataframe

enter image description here

enter image description here

我想在数据帧上执行条件减法(显示为第一张图片)。

基本上,这就是我想要做的事情:

  1. 在我和你之间减去食物和衣物的col1和col2的值,并为差异创建新行。
  2. 由于第一行有食物'并且'我'而第三排有食物'并且'你'你从第一行中减去第三行的col1和col2的值 (300 - 600 = -300,和200 - 500 = -300)。

    由于第二排有衣服'并且'我'第四排有衣服'并且'你'你从第二行中减去第四行的col1和col2的值(500 - 200 = 300和600 - 700 = -100)。

    如何使用Pandas数据框实现此功能?

2 个答案:

答案 0 :(得分:2)

你可以使用pd.concatgroupby这样做,并利用Pandas基于索引的数据内在对齐:

输入df:

df = pd.DataFrame({'type1':['food','clothing','food','clothing'],'type2':['me','me','you','you'],'col1':[300,500,600,200],'col2':[200,600,500,700]})


pd.concat([df.set_index(['type1','type2'])
  .groupby('type1')
  .apply(lambda x: x.iloc[0]-x.iloc[1])
  .assign(type2='us')
  .set_index('type2', append=True),
  df.set_index(['type1','type2'])]).reset_index()

对于年龄大于0.20.0的熊猫

pd.concat([df.set_index(['type1','type2'])
  .groupby(level=0)
  .apply(lambda x: x.iloc[0]-x.iloc[1])
  .assign(type2='us')
  .set_index('type2', append=True),
  df.set_index(['type1','type2'])]).sort_index(level=[1,0]).reset_index()

输出:

      type1 type2  col1  col2
0  clothing    us   300  -100
1      food    us  -300  -300
2      food    me   300   200
3  clothing    me   500   600
4      food   you   600   500
5  clothing   you   200   700

答案 1 :(得分:1)

使用eval

进行此操作的方法
df \
  .set_index(['type2', 'type1']).unstack().T \
  .eval('us = me - you', inplace=False) \
  .T.stack().reset_index()

  type2     type1  col1  col2
0    me  clothing   500   600
1    me      food   300   200
2   you  clothing   200   700
3   you      food   600   500
4    us  clothing   300  -100
5    us      food  -300  -300
相关问题