计算满足另一列中的条件的列之间的差异[重复]

问题描述 投票:0回答:1

我有一个数据集如下:

import pandas as pd
df = pd.DataFrame(
    {"Time": [1,2,3,1,2,3],
     "Prop1": ["A","B","A","A","B","B"],
     "Prop2": [4, 5, 1, 5, 4, 3]})
时间 提案1 提案2
1 A 4
2 B 5
3 A 1
1 A 5
2 B 4
3 B 3

我想要的是差异...

  1. 在每个时间步
  2. 对于 Prop1 值
  3. Prop2 之间

从这个数据集中我想收到类似的东西......

时间 提案1 提案2 Prop2Diff
1 A 4 NaN
2 B 5 NaN
3 A 1 NaN
1 A 5 (5-4)= 1
2 B 4 (4-5)=-1
3 B 3 NaN

我知道有 .diff() 函数,但我不确定如何应用我想要的条件类型。

这是为了消除我的脚本中的深层循环,我已经做到了:

time = df["Time"].unique()
for cTime in time:
    for prop1 in df[df["Time"] == cTime,"Prop1"].unique():
        df.loc[(df["Time"]==cTime) & (df["Prop1"] == prop1] = cDF["Prop2"][1] - cDF["Prop2"][0]

以及循环的其他变体。

这是在非常大的数据集上运行,因此我可以删除的每个循环都非常有帮助。

python pandas diff
1个回答
1
投票

代码

df['Prop2Diff'] = df.groupby(['Time', 'Prop1'])['Prop2'].diff()

df

   Time Prop1  Prop2  Prop2Diff
0     1     A      4        NaN
1     2     B      5        NaN
2     3     A      1        NaN
3     1     A      5        1.0
4     2     B      4       -1.0
5     3     B      3        NaN
© www.soinside.com 2019 - 2024. All rights reserved.