python - Pandas 的条件转移

标签 python pandas dataframe

以下 pandas DataFrame 是我需要处理的一个示例:

       Group   Amount
1      1       100
2      1       300
3      1       400
4      1       700
5      2       500
6      2       900

这是我想要的计算后的结果:

       Group   Amount   Difference
1      1       100      100
2      1       300      200
3      1       400      100
4      1       700      300
5      2       500      500
6      2       900      400

我知道 df["Difference"] = df["Amount"] - df["Amount"].shift(-1) 可以产生所有行之间的差异,但是我能为我遇到的问题做什么像这样需要一个group作为条件吗?

最佳答案

groupby 在“Group”上,并在“Amount”列上调用 transform,另外调用 fillna 并传递“Amount”列:

In [110]:
df['Difference'] = df.groupby('Group')['Amount'].transform(pd.Series.diff).fillna(df['Amount'])
df
​
Out[110]:
   Group  Amount  Difference
1      1     100         100
2      1     300         200
3      1     400         100
4      1     700         300
5      2     500         500
6      2     900         400

关于python - Pandas 的条件转移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36159569/

相关文章:

python - 如何使用 Python 确保字符串仅为数字,然后将其转换为整数

python - 重新排列 linregress python 中的标题

python - pandas 引发日期时间对象的值错误

python - 如何在一列中找到三个输入最多的值?

python - ForLoop 迭代作为 Django 模板中的列表索引

python - 为什么 pyserial 在有 11 个参数时说我已经给出了 12 个参数?

python - 在 Python 中使用 OpenCV 从图像中裁剪人脸

python - 如何使用 Pandas 在年份变化时继续周数

根据不同列中的值替换 data.frame 列中的值

python - 如何解决 "GeoDataFrame object has not attribute..."错误