【问题标题】:Get index where value changes in pandas dataframe column获取熊猫数据框列中值变化的索引
【发布时间】:2018-02-07 20:53:34
【问题描述】:

我正在尝试扩展我的熊猫技能。我有一个看起来像这样的熊猫数据框:

df

      Group 1     Group 2            Product ID
0   Products      International      X11
1   Products      International      X11
2   Products      Domestic           X11
3   Products      Domestic           X23
4   Services      Professional       X23
5   Services      Professional       X23
6   Services      Analytics          X25

我正在尝试使用一些 pandas 功能来获取第 1 组和第 2 组的值发生变化的索引。我知道我可能必须逐列查看,并将这些索引附加到不同的列表中。

我参考了这个问题Find index where elements change value pandas dataframe,这是我能找到的最接近的类似问题。

我试图得到这样的输出:

 Group 1 changes = [0,4]
 Group 2 changes = [0,2,4,6]

如果一列中的两个值相同,pandas 是否有任何内置功能可以快速引用,然后获取该索引?

我的所有数据都是按组排序的,因此如果解决方案确实涉及逐行迭代,则不应遇到任何问题。

非常感谢任何帮助!

【问题讨论】:

    标签: python pandas iteration


    【解决方案1】:

    使用

    In [91]: df.ne(df.shift()).apply(lambda x: x.index[x].tolist())
    Out[91]:
    Group 1             [0, 4]
    Group 2       [0, 2, 4, 6]
    Product ID       [0, 3, 6]
    dtype: object
    
    In [92]: df.ne(df.shift()).filter(like='Group').apply(lambda x: x.index[x].tolist())
    Out[92]:
    Group 1          [0, 4]
    Group 2    [0, 2, 4, 6]
    dtype: object
    

    也适用于字典,

    In [107]: {k: s.index[s].tolist() for k, s in df.ne(df.shift()).filter(like='Group').items()}
    Out[107]: {'Group 1': [0L, 4L], 'Group 2': [0L, 2L, 4L, 6L]}
    

    【讨论】:

    • 你是英雄和天使合二为一。
    • df.ne ➙ 不相等,将另一个数据帧作为输入 df.shift() ➙ 将索引移动 1(默认)
    【解决方案2】:

    这是一种非熊猫解决方案。我喜欢它,因为它很直观,不需要了解大型 pandas 库。

    changes = {}
    
    for col in df.columns:
        changes[col] = [0] + [idx for idx, (i, j) in enumerate(zip(df[col], df[col][1:]), 1) if i != j]
    
    # {'Group 1': [0, 4], 'Group 2': [0, 2, 4, 6], 'Product ID': [0, 3, 6]}
    

    【讨论】:

    • 这也很好用。这个网站有时让我很开心。谢谢!
    猜你喜欢
    • 2021-01-19
    • 2023-02-10
    • 2022-01-25
    • 1970-01-01
    • 2016-08-06
    • 2017-12-23
    • 2018-08-04
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多