Python Pandas : conditional subtraction

标签 python pandas dataframe

enter image description here

enter image description here

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

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

  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 数据框实现此功能?

最佳答案

您可以使用 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

关于Python Pandas : conditional subtraction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45172463/

相关文章:

python - 多索引 - 获取每个第一个索引的第二个索引的最大值

python - 当 'ID' 为 1 时,如何创建一个新列插入分组列 'interaction'(及时)的单元格值

python - Pastebin API : Getting Unlisted Paste Always

python - Django HTTP 响应未正确命名文件

python - "sys-package-mgr*: can' t 创建包缓存目录“当使用 Jython 运行 python 脚本时

python - 复制 Pandas 数据框中的行

pandas - 如何通过数据框中的数据计算频率?

pandas - 如何使用脚本的凭据从 gcs 将 .csv 放入数据框中?

PYTHON - 合并日期索引上的两个数据帧

python - pip2 和 pip3 的不同自定义安装位置