简体   繁体   English

比较数据框中每一列的前一行值

[英]Comparing previous row values of every column in a dataframe

I have a similar question to this one .我有这种类似的问题一个

I have a dataframe with an ID column and a counter column for this idea which looks like this:对于这个想法,我有一个带有 ID 列和计数器列的数据框,如下所示:

ID counter valueA   valueB
A   1       10        1
A   2       10        1
A   3       5         1
B   1       1         2
B   2       1         3
B   3       2         4
B   4       3         4
...

How can i count the row changes per column with a 1 in the dataframe, so that the dataframe looks like:我如何计算数据框中每列的行更改为 1,以便数据框如下所示:

ID counter valueA   valueB
A   1       0         0
A   2       0         0
A   3       1         0
B   1       0         0
B   2       0         1
B   3       1         1
B   4       1         1
...

So that everytime a value change in the columns (only if it is the same ID, the counter should not be marked) I got a marker with 1. Note that I have more value columns, this two are only an example.因此,每次列中的值更改时(仅当它是相同的 ID 时,不应标记计数器)我得到一个带 1 的标记。请注意,我有更多的值列,这两个只是一个例子。

Use:用:

df = pd.DataFrame({'ID': ['A', 'A', 'A', 'B', 'B', 'B', 'B'], 'counter': [1, 2, 3, 1, 2, 3, 4], 'valueA': [10, 10, 5, 1, 1, 2, 3], 'valueB': [1, 1, 1, 2, 3, 4, 4]})

print (df)打印 (df)


c = ['valueA','valueB']
df[c] = df[c].ne(df[c].groupby(df['ID']).shift().bfill()).astype(int)
print (df)
  ID  counter  valueA  valueB
0  A        1       0       0
1  A        2       0       0
2  A        3       1       0
3  B        1       0       0
4  B        2       0       1
5  B        3       1       1
6  B        4       1       0

For counter per groups I try this solution, but still different output:对于每个组的计数器,我尝试使用此解决方案,但输出仍然不同:

df[c] = df[c].ne(df[c].groupby(df['ID']).shift().bfill()).groupby(df['ID']).cumsum()
print (df)
  ID  counter  valueA  valueB
0  A        1       0       0
1  A        2       0       0
2  A        3       1       0
3  B        1       0       0
4  B        2       0       1
5  B        3       1       2
6  B        4       2       2

Note: For a success the newest pandas version should be installed注意:为了成功,应该安装最新的熊猫版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM