我有一个数据框:
keyword val
0 nt 0.93
1 atm 0.94
2 bank 1.00
3 long 1.02
4 number 1.11
5 get 2.20
6 money 3.50
7 account 3.80
8 deposit 3.90
9 card 5.00
10 credit 0.8
11 debit 1.23
我想找出每单位价值范围内的关键字数量 即从0.9-1 => [nt,atm] => 2 从1-1.1 => [bank,long,number] => 3,依此类推
答案 0 :(得分:1)
尝试使用groupby
进行某些列值修改,然后在count
列上使用'keyword'
:
>>> df.groupby(df['val'].astype(int))['keyword'].count()
val
0 3
1 4
2 1
3 3
4 1
Name: keyword, dtype: int64
编辑:
>>> df.groupby(df['val'].apply("{:.1f}".format))['keyword'].count()
val
0.8 1
0.9 2
1.0 2
1.1 1
1.2 1
2.2 1
3.5 1
3.8 1
3.9 1
5.0 1
Name: keyword, dtype: int64
如果四舍五入(尽管1.9
与1.1
不在同一个组中):
>>> df.groupby(df['val'].round(1))['keyword'].count()
val
0.8 1
0.9 2
1.0 2
1.1 1
1.2 1
2.2 1
3.5 1
3.8 1
3.9 1
5.0 1
Name: keyword, dtype: int64
答案 1 :(得分:1)
在此处将pd.cut()
与groupby()
一起使用:
bins=[0,1,2,3,5]
df.groupby(pd.cut(df.val,bins)).keyword.apply(list)
val
(0, 1] [nt, atm, bank]
(1, 2] [long, number]
(2, 3] [get]
(3, 5] [money, account, deposit, card]
用于计数:
df.groupby(pd.cut(df.val,bins)).keyword.size()
val
(0, 1] 3
(1, 2] 2
(2, 3] 1
(3, 5] 4
您可以自定义垃圾箱,例如:
bins=[0,0.99,1,1.99,2,2.99,3,3.99,4,4.99,5]
df.groupby(pd.cut(df.val,bins)).keyword.size()
val
(0.0, 0.99] 2
(0.99, 1.0] 1
(1.0, 1.99] 2
(1.99, 2.0] 0
(2.0, 2.99] 1
(2.99, 3.0] 0
(3.0, 3.99] 3
(3.99, 4.0] 0
(4.0, 4.99] 0
(4.99, 5.0] 1