![](/img/trans.png)
[英]Perform cumulative sum on a column of pandas dataframe ignoring NAN
[英]How to perform a cumulative sum of distinct values in pandas dataframe
我有這樣的數據幀:
id date company ......
123 2019-01-01 A
224 2019-01-01 B
345 2019-01-01 B
987 2019-01-03 C
334 2019-01-03 C
908 2019-01-04 C
765 2019-01-04 A
554 2019-01-05 A
482 2019-01-05 D
我希望獲得“公司”專欄隨時間推移的唯一值的累計數量。 因此,如果公司稍后出現,則不再計算在內。
我的預期輸出是:
date cumulative_count
2019-01-01 2
2019-01-03 3
2019-01-04 3
2019-01-05 4
我試過了:
df.groupby(['date']).company.nunique().cumsum()
但是,如果同一家公司出現在不同的日期,這個雙重計算。
使用duplicated
+ cumsum
+ last
m = df.duplicated('company')
d = df['date']
(~m).cumsum().groupby(d).last()
date
2019-01-01 2
2019-01-03 3
2019-01-04 3
2019-01-05 4
dtype: int32
另一種嘗試修復anky_91的方法
(df.company.map(hash)).expanding().apply(lambda x: len(set(x)),raw=True).groupby(df.date).max()
Out[196]:
date
2019-01-01 2.0
2019-01-03 3.0
2019-01-04 3.0
2019-01-05 4.0
Name: company, dtype: float64
來自anky_91
(df.company.astype('category').cat.codes).expanding().apply(lambda x: len(set(x)),raw=True).groupby(df.date).max()
這需要比anky的答案更多的代碼,但仍然適用於示例數據:
df = df.sort_values('date')
(df.drop_duplicates(['company'])
.groupby('date')
.size().cumsum()
.reindex(df['date'].unique())
.ffill()
)
輸出:
date
2019-01-01 2.0
2019-01-03 3.0
2019-01-04 3.0
2019-01-05 4.0
dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.