python - 如果索引不同,如何停止在 Pandas 中移动列

标签 python pandas dataframe

我有这样的数据

enter image description here .

我想使用 pandas shift 并在 之间减去值。这是我正在使用的 code

df['Difference'] = (df['A'] - df['A'].shift(-1))

这是我得到的输出(正如预期的那样)。

enter image description here

如果 index ( Id) 不同,如何防止 pandascolumns 之间进行减法。我只想在 index 相同时减去。我的愿望输出是这样的。使用 df.shift(-1, axis = 0) 也没有解决。 enter image description here

有什么建议吗?

最佳答案

可以先groupby 'id':

In [156]: df.assign(
     ...:   new_col=df.groupby('id').diff(-1)
     ...: )
Out[156]: 
    A  id  new_col
0   6   1      2.0
1   4   1     -7.0
2  11   1      NaN
3   7   2     -2.0
4   9   2     -4.0
5  13   2      NaN

关于python - 如果索引不同,如何停止在 Pandas 中移动列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474031/

相关文章:

python - 将 raw_input 转换为 python 表达式

python - 如何像我们在 pyspark withColumn 中那样在 pandas 中动态创建新列

python-3.x - 替换数据框列中每个值的天数

r - 如何使用 igraph 包从数据框中构建图表?

python - 是否有一种 pythonic 方法来获取数据帧之间的差异?

python - 创建一个新列,将列表中其他两列的内容组合在一起

python - Pandas 中返回数字而不是书籍的按位运算?

python - Pandas Dataframe 按列分组

r - 将 R 对象导入 Python 的最佳方法?

python - 以系列结尾的 Pandas OR 语句包含