我有一个包含数值的数据框列:
df['percentage'].head()
46.5
44.2
100.0
42.12
我希望将该列显示为bin counts
bins = [0, 1, 5, 10, 25, 50, 100]
我怎样才能得到带有值计数的结果?
[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...
发布于 2017-07-24 14:14:28
您可以使用pandas.cut
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
...and,然后是value_counts
或groupby
,然后聚合size
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
默认情况下,cut
返回categorical
。
像Series.value_counts()
这样的Series
方法将使用所有类别,即使数据中没有某些类别,operations in categorical。
发布于 2022-02-25 00:29:35
我们也可以使用np.select
bins = [0, 1, 5, 10, 25, 50, 100]
df['groups'] = (np.select([df['percentage'].between(i, j, inclusive='right')
for i,j in zip(bins, bins[1:])],
[1, 2, 3, 4, 5, 6]))
输出:
percentage groups
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
https://stackoverflow.com/questions/45273731
复制相似问题