【问题标题】:How can I count value changes based on 2 other columns?如何根据其他 2 列计算值更改?
【发布时间】:2019-08-15 14:22:55
【问题描述】:

我有以下数据框:

import pandas as pd

data = [{'testid': 'testid_1', 'value':15},
{'testid': 'testid_1', 'value':15},
{'testid': 'testid_1', 'value':20},
{'testid': 'testid_1', 'value':20},
{'testid': 'testid_1', 'value':15},
{'testid': 'testid_1', 'value':15},
{'testid': 'testid_2', 'value':215},
{'testid': 'testid_2', 'value':215},
{'testid': 'testid_3', 'value':215},
{'testid': 'testid_3', 'value':69},
{'testid': 'testid_3', 'value':215}]

df = pd.DataFrame(data)

df
Out[5]: 
      testid  value
0   testid_1     15
1   testid_1     15
2   testid_1     20
3   testid_1     20
4   testid_1     15
5   testid_1     15
6   testid_2    215
7   testid_2    215
8   testid_3    215
9   testid_3     69
10  testid_3    215

我一直在寻找的是创建一个名为 counter 或类似名称的列,以数字方式跟踪列 testidvalues 的变化。

每次testid 更改时,计数器都应重置为1,保持不变,而values 不更改,如果更改添加1

这是我想要的输出:

      testid  value  counter
0   testid_1     15        1
1   testid_1     15        1
2   testid_1     20        2
3   testid_1     20        2
4   testid_1     15        3
5   testid_1     15        3
6   testid_2    215        1
7   testid_2    215        1
8   testid_3    215        1
9   testid_3     69        2
10  testid_3    215        3

请注意,如果 testid 发生变化,则计数器将独立于 value,返回到 1

我一直在尝试使用 shift() 和其他东西进行比较,但我的主要问题是根据更改跟踪计数器

非常感谢,我将不胜感激

【问题讨论】:

    标签: python pandas counter


    【解决方案1】:

    你的情况

    df['newid']=df.groupby('testid').value.apply(lambda x : x.diff().ne(0).cumsum())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 2022-07-08
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多