我有以下虚拟df:
data = {'count':[11, 113, 53, 416, 3835, 143, 1, 1, 1, 2, 3, 4, 3, 4, 4, 6, 7, 7, 8,8,8,9]}
df = pd.DataFrame(data)并想要创造这样的情节:

也就是说,我想根据频率将df排序为组。
共6组。组1-2表示列count中的所有条目,这些条目要么是1或2,要么是第3-4组--列count中的所有条目都是3或4等等。
然后我试了一下:
new_df = pd.DataFrame(columns=['1-2', '3-4', '5-6', '7-8', '9-10', '>10'])
new_df['1-2'] = df[df['count'] > 0 & (df['count'] <= 2)].count()在第一至第二组就有22次了,所以这里有点不对劲。
发布于 2021-06-09 13:43:08
对于第一个条件(df['count']>0),也需要括号:
new_df['1-2'] = df[(df['count']>0) & (df['count']<=2)].count()
new_df['3-4'] = df[(df['count']>2) & (df['count']<=4)].count()
new_df['5-6'] = df[(df['count']>4) & (df['count']<=6)].count()
new_df['7-8'] = df[(df['count']>6) & (df['count']<=8)].count()
new_df['9-10'] = df[(df['count']>8) & (df['count']<=10)].count()
new_df['>10'] = df[(df['count']>10)].count()情节:
new_df.T.plot.bar(fill=False, edgecolor="red")

发布于 2021-06-09 13:48:52
您可能希望为此使用pd.cut,因为您可以指定回收箱和标签,因此它只是简单的分组、计数和绘图。
data = {'count':[11, 113, 53, 416, 3835, 143, 1, 1, 1, 2, 3, 4, 3, 4, 4, 6, 7, 7, 8,8,8,9]}
df = pd.DataFrame(data)
# Create bins with labels
bins = pd.IntervalIndex.from_tuples([(0, 2), (2, 4), (4, 6), (6, 8), (8,10), (10, 100000)])
df['bins'] = pd.cut(df['count'], bins=bins)
# Plot the bin counts
df.groupby('bins').count().plot(kind='bar')

https://stackoverflow.com/questions/67905281
复制相似问题