如何在 python 中计数,并直接在数据框中创建列(多列分组)
How to countifs in python, and directly create column in data frame (grouping with multiple columns)
目前我正在使用 excel 或电子表格来做 countifs
,问题是我们如何才能在 pandas
中得到这个结果
目前我成功使用了这个方法
item_view['size'] = item_view.groupby('status_id')['date'].transform(len)
qfilter_1 = qgrid.show_grid(item_view)
qfilter_1
但是结果是count all match,我想实现的是图片,非常感谢你的帮助谢谢
这应该可以解决问题:
import numpy as np
item_view['i'] = np.arange(len(item_view))
item_view['countifs'] = item_view.groupby(['status id','date']).transform('count')
哪个prints
:
date status id i countifs
0 2020-11-30 AA 0 2
1 2020-11-30 DD 1 2
2 2020-11-30 AA 2 2
3 2020-11-30 DD 3 2
4 2020-11-30 EE 4 1
5 2020-11-30 FF 5 1
6 2020-11-23 GG 6 2
7 2020-11-23 DD 7 2
8 2020-11-23 EE 8 1
9 2020-11-23 FF 9 1
10 2020-11-23 GG 10 2
11 2020-11-23 DD 11 2
然后 drop
我们创建的新 i
列:
item_view.drop('i',axis=1,inplace=True)
获得您所需要的:
date status id countifs
0 2020-11-30 AA 2
1 2020-11-30 DD 2
2 2020-11-30 AA 2
3 2020-11-30 DD 2
4 2020-11-30 EE 1
5 2020-11-30 FF 1
6 2020-11-23 GG 2
7 2020-11-23 DD 2
8 2020-11-23 EE 1
9 2020-11-23 FF 1
10 2020-11-23 GG 2
11 2020-11-23 DD 2
然后,如果您只想保留唯一的行,您可以 drop_duplicates()
目前我正在使用 excel 或电子表格来做 countifs
,问题是我们如何才能在 pandas
目前我成功使用了这个方法
item_view['size'] = item_view.groupby('status_id')['date'].transform(len)
qfilter_1 = qgrid.show_grid(item_view)
qfilter_1
但是结果是count all match,我想实现的是图片,非常感谢你的帮助谢谢
这应该可以解决问题:
import numpy as np
item_view['i'] = np.arange(len(item_view))
item_view['countifs'] = item_view.groupby(['status id','date']).transform('count')
哪个prints
:
date status id i countifs
0 2020-11-30 AA 0 2
1 2020-11-30 DD 1 2
2 2020-11-30 AA 2 2
3 2020-11-30 DD 3 2
4 2020-11-30 EE 4 1
5 2020-11-30 FF 5 1
6 2020-11-23 GG 6 2
7 2020-11-23 DD 7 2
8 2020-11-23 EE 8 1
9 2020-11-23 FF 9 1
10 2020-11-23 GG 10 2
11 2020-11-23 DD 11 2
然后 drop
我们创建的新 i
列:
item_view.drop('i',axis=1,inplace=True)
获得您所需要的:
date status id countifs
0 2020-11-30 AA 2
1 2020-11-30 DD 2
2 2020-11-30 AA 2
3 2020-11-30 DD 2
4 2020-11-30 EE 1
5 2020-11-30 FF 1
6 2020-11-23 GG 2
7 2020-11-23 DD 2
8 2020-11-23 EE 1
9 2020-11-23 FF 1
10 2020-11-23 GG 2
11 2020-11-23 DD 2
然后,如果您只想保留唯一的行,您可以 drop_duplicates()