获取pandas dataframe列中值更改的索引 [英] Get index where value changes in pandas dataframe column

查看:815
本文介绍了获取pandas dataframe列中值更改的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力扩展我的熊猫技能。我有一个像这样的pandas数据框:

I am trying to expand my pandas skills. I have a pandas dataframe that looks like this :

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组更改。我知道我可能不得不逐列,并将这些索引附加到不同的列表中。

I am trying to use some pandas functionality to get the index where the values of Group 1 and Group 2 change. I understand that I will probably have to go column by column, and append these indices into different lists.

我引用了这个问题查找元素更改值pandas dataframe的索引,这是我能找到的最接近的类似问题。

I have referenced this question Find index where elements change value pandas dataframe which was the closest similar question that I can find.

我想得到这样的输出:

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

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

Is there any sort of built in functionality that pandas has that can quickly reference if two values in a column are the same, and then grab that index?

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

All of my data is sorted by group, so shouldn't run into any problems if the solution does involve iterating row by row.

非常感谢任何帮助!

推荐答案

使用

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

同样适用于dict,

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]}

这篇关于获取pandas dataframe列中值更改的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆