【问题标题】:Error in plotting of frequency histogram from csv data从 csv 数据绘制频率直方图的错误
【发布时间】:2020-05-21 17:56:36
【问题描述】:

我正在 python3 上使用带有 pandas 模块的 csv 文件。 csv文件由5列组成:职位、公司名称、职位描述、评论数量、职位位置;我想绘制一个频率直方图,在这里我只选择包含“机械工程师”一词的工作,并找到“机械工程师”工作的 5 个最常见位置的频率。

所以,我定义了一个变量 engloc 来存储所有“机械工程师”的工作。

engloc=df[df.position.str.contains('mechanical engineer|mechanical engineering', flags=re.IGNORECASE, regex=True)].location

并使用我在网上找到的代码用 matplotlib 绘制直方图

 x = np.random.normal(size = 1000)
 plt.hist(engloc, bins=50)
 plt.gca().set(title='Frequency Histogram ', ylabel='Frequency');

但它是这样打印的

我如何绘制一个正确的频率直方图,它只使用 5 个最常见的位置来绘制包含“机械工程师”字样的工作,而不是将所有位置都放在图中?

这是来自 csv 文件的示例

【问题讨论】:

  • 如果您分享您的数据,可能会有人愿意帮助您。有关完整说明,请参阅minimal reproducible example
  • 我应该包括某些部分的屏幕截图还是在问题中写一些数据的参数?
  • 一个“有代表性的”数据样本,允许绘制一个有意义的直方图,按文本输入。更好地链接到完整数据。
  • 将您的数据发布为文本,而不是屏幕截图

标签: python python-3.x pandas csv matplotlib


【解决方案1】:

以下内容应该可以帮助您处理数字数据:

import numpy as np
counts_, bins_ = np.histogram(englog.values)
filtered = [(c,b) for (c,b) in zip(counts_,bins_) if counts_>=5]
counts, bins = list(zip(*filtered))
plt.hist(bins[:-1], bins, weights=counts)

对于字符串类型试试:

from collections import Counter 
coords, counts = list(zip(*Counter(englog.values).most_common(5)))
plt.bar(coords, counts)

【讨论】:

  • 它给出了一个类似这样的错误“TypeError: ufunc 'isfinite' not supported for the input types, and the input can not be safely coerced to any supported types based on the cast rule ''safe'' .
  • 遗憾的是第二个也报错了。TypeError: list() 最多接受 1 个参数(给定 5 个)
  • @Ayano 这能解决您的问题吗?如果是这样,您可能会考虑接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2020-01-21
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多