Python 如何绘制按计数值排序的列字
此代码计算列中的单词数Python 如何绘制按计数值排序的列字,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,此代码计算列中的单词数 df['businesstype'].value_counts() #value count 我的问题是,现在如何在businesstype列中绘制计数最高的10或5个单词 df.head(10)['businesstype'].value_counts().plot.bar() 这是可行的,但它按轴计数。我的csv数据按轴排序,而不是按值计数 这个问题可能很简单,但我正在学习,我还没有找到任何答案 数据帧如下所示: Index(['Rang 2014', '
df['businesstype'].value_counts() #value count
我的问题是,现在如何在businesstype
列中绘制计数最高的10或5个单词
df.head(10)['businesstype'].value_counts().plot.bar()
这是可行的,但它按轴计数。我的csv数据按轴排序,而不是按值计数
这个问题可能很简单,但我正在学习,我还没有找到任何答案
数据帧如下所示:
Index(['Rang 2014', 'Unnamed: 1', 'Rang 2013','unternehmen' , 'Sitz',
'Umsatz (Mrd. €)', 'Gewinn/Verlust (Mio. €)', 'Mitarbeiter weltweit',
'businestype'],
dtype='object')
我还检查了pd选项
max rows
没有任何更改,如果我设置max rows,只打印上半部分和下半部分。您可以简单地在value\u count
系列中打印条目1-5,但如果与以下条目有关联,则会扭曲输出。更好的战略是:
import pandas as pd
from matplotlib import pyplot as plt
#number of top entries
nmax = 5
#fake data generation
import numpy as np
np.random.seed(1234)
n = 30
df = pd.DataFrame({"A": np.random.choice(list("XYZUVWKLM"), n), "B": np.random.randint(1, 10, n)})
#create value count series from A
plot_df = df["A"].value_counts()
#plot the two strategies into different panels for better comparison
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
#strategy 1: simply plot the first nmax rows
plot_df[:nmax].plot.bar(ax=ax1, rot=0)
ax1.set_title("First nmax entries")
#better approach with strategy 2:
#find value for top nmax entry in case there is a tie with the following entries
val_for_nmax = plot_df[nmax-1]
#plot columns that have no less than this value
plot_df[plot_df>=val_for_nmax].plot.bar(ax=ax2, rot=45)
ax2.set_title("Take care of tie values")
plt.show()
样本输出:
您是否尝试将排序顺序设置为True/False以查看是否有帮助。value_counts(sort=False)感谢这项工作,这对我来说是个很好的练习:)我祝圣诞节快乐,很高兴这解决了问题。我们都是来学习的。我如何用策略1规划按业务类型值计算的unternehmen(companyname)?我能换x轴吗?你不能。现在问题不同了;您要求打印一个系列,因此在该打印系列中找不到其余的数据帧信息(其中不包含关于
B
的信息)。我建议你用重新定义的问题问一个新问题,并提供一个用户可以复制粘贴以测试其策略的方法。它不一定是真实的数据集,只是一个玩具数据集,就像我的答案中反映真实事物特征的数据集一样。好的,谢谢,我记得在我的新问题帖子中提到了这一点