对于一列中的关键字(字符串)和另一列中的值(浮点数),我想计算每单位值范围内的ok关键字的数量

时间:2019-05-31 05:27:50

标签: python pandas

我有一个数据框:

            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,依此类推

2 个答案:

答案 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.91.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