【问题标题】:Python Pandas: conditional subtractionPython Pandas:条件减法
【发布时间】:2017-07-18 16:30:23
【问题描述】:

我想对数据帧进行条件减法(如第一张图片所示)。

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

  1. 减去我和你之间食物和衣服的 col1 和 col2 的值,并为差异创建新行。

由于第一行有“food”和“me”,第三行有“food”和“you”,所以从第一行中减去第三行的 col1 和 col2 的值 (300 - 600 = -300,200 - 500 = -300)。

由于第二行有“clothing”和“me”,第四行有“clothing”和“you”,所以从第二行中减去第四行的 col1 和 col2 的值(500 - 200 = 300和 600 - 700 = -100)。

如何使用 Pandas 数据框实现这一点?

【问题讨论】:

  • transport dataframe pandas ,如 df.T 并附加列然后将其传输回来
  • 除了接受@ScottBoston 的答案外,请考虑对它进行投票。谢谢。

标签: python pandas dataframe


【解决方案1】:

您可以使用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 之前的 Pandas

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

【讨论】:

  • 嗨,我试过你写的代码,但它给了我 KeyError: 'type1' mssage。
  • hrm...我刚刚剪切并粘贴了确切的代码,它运行良好。
  • 这很奇怪......嗯......为什么我得到 KeyError: 'type1' 错误哈哈
  • 你同时运行这两个语句吗?
  • 是的,我是。我想当我到达“.groupby('type1')”部分时会收到错误消息。
【解决方案2】:

一种使用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

【讨论】:

  • 评估! +1 我需要更多地使用它。
猜你喜欢
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2017-10-16
  • 2020-10-05
  • 2015-12-11
  • 2018-10-03
  • 1970-01-01
相关资源
最近更新 更多