熊猫-不同值的滚动累积计数

时间:2020-02-06 12:19:30

标签: python python-3.x pandas dataframe

我有这样的df:

GET file:///C:/styles.2039b83b.css net::ERR_FILE_NOT_FOUND
2index.html:22 GET file:///C:/img/logo.svg net::ERR_FILE_NOT_FOUND
index.html:25 GET file:///C:/styles.1c10c9f3.js net::ERR_FILE_NOT_FOUND
index.html:27 GET file:///C:/runtime~main.936f7875.js net::ERR_FILE_NOT_FOUND
index.html:29 GET file:///C:/main.5d1426ac.js net::ERR_FILE_NOT_FOUND
index.html:31 GET file:///C:/common.46a79f08.js net::ERR_FILE_NOT_FOUND
index.html:33 GET file:///C:/2.d1c81d83.js net::ERR_FILE_NOT_FOUND
index.html:35 GET file:///C:/1be78505.8a34320a.js net::ERR_FILE_NOT_FOUND
index.html:37 GET file:///C:/20ac7829.5dd9332a.js net::ERR_FILE_NOT_FOUND
index.html:39 GET file:///C:/17896441.f0de57b0.js net::ERR_FILE_NOT_FOUND
index.html:41 GET file:///C:/7366bc9d.edc04dbd.js net::ERR_FILE_NOT_FOUND

输出:

df = pd.DataFrame({
         'date': ['01/01/2020', '01/01/2020', '01/01/2020', '02/01/2020', '02/01/2020', '03/01/2020', '03/01/2020'],
         'id': [101, 102, 103, 101, 104, 105, 106]
})

我需要像这样的不同值的累积计数:

         date   id
0  01/01/2020  101
1  01/01/2020  102
2  01/01/2020  103
3  02/01/2020  101
4  02/01/2020  104
5  03/01/2020  105
6  03/01/2020  106

我尝试了类似df.groupby(['date'])。nunique()之类的方法,但是显然这是不对的,因为它提供了每个日期的唯一计数,没有我需要的滚动唯一计数。

2 个答案:

答案 0 :(得分:3)

我认为有必要先按DataFrame.drop_duplicates删除每个id的重复项,然后按GroupBy.size删除每个date的计数,并按Series.cumsum加上累计和:

df = df.drop_duplicates('id').groupby('date').size().cumsum().reset_index(name='id')
print (df)
         date  id
0  01/01/2020   3
1  02/01/2020   4
2  03/01/2020   6

答案 1 :(得分:2)

或者我们可以使用DataFrame.duplicated

(~df.duplicated('id')).groupby(df['date']).sum().cumsum().rename('id').reset_index()

         date   id
0  01/01/2020  3.0
1  02/01/2020  4.0
2  03/01/2020  6.0