我在日期框('df1')中具有按系列'状态'细分的累积数据(系列'cumulative_count'),并且我想在数据框中创建一个新系列,该系列显示按'状态”。
所以:
df1 = pd.DataFrame({'date': ['2020-01-03','2020-01-03','2020-01-03','2020-01-04','2020-01-04','2020-01-04','2020-01-05','2020-01-05','2020-01-05'],'state': ['NJ','NY','CT','NJ','NY','CT','NJ','NY','CT'], 'cumulative_count': [1,3,5,3,6,7,19,15,20]})
...已转换为添加了新的序列(“增量计数”),其中增量计数是按日期计算的,但也可以按状态进行细分,生成的结果是...
df2 = pd.DataFrame({'date': ['2020-01-03','2020-01-03','2020-01-03','2020-01-04','2020-01-04','2020-01-04','2020-01-05','2020-01-05','2020-01-05'],'state': ['NJ','NY','CT','NJ','NY','CT','NJ','NY','CT'], 'cumulative_count': [1,3,5,3,6,7,19,15,20],'incremental_count': [1,3,5,2,3,2,16,9,13]})
任何有关如何执行此操作的建议将不胜感激。谢谢!
答案 0 :(得分:0)
由于您的DataFrame已按'date'
排序,因此您希望在每个状态组中使用diff
。然后fillna
获取每个州内第一个日期的正确值。
df1['incremental_count'] = (df1.groupby('state')['cumulative_count'].diff()
.fillna(df1['cumulative_count'], downcast='infer'))
date state cumulative_count incremental_count
0 2020-01-03 NJ 1 1
1 2020-01-03 NY 3 3
2 2020-01-03 CT 5 5
3 2020-01-04 NJ 3 2
4 2020-01-04 NY 6 3
5 2020-01-04 CT 7 2
6 2020-01-05 NJ 19 16
7 2020-01-05 NY 15 9
8 2020-01-05 CT 20 13