【问题标题】:"TypeError: cannot convert the series to <type 'float'>" when plotting pandas series data绘制熊猫系列数据时“TypeError:无法将系列转换为 <type 'float'>”
【发布时间】:2018-03-12 18:47:48
【问题描述】:

尝试使用 matplotlib 绘制条形图时出现错误。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
source_data= pd.read_csv("ehresp_2015.csv")

然后我从我需要的数据集中提取两列

results_1 = source_data[["EUGROSHP","EUGENHTH"]]

摆脱负值

results_1_new = results_1[results_1>0]

绘制数据

x=results_1_new['EUGROSHP']
y=results_1_new['EUGENHTH']
plt.bar([x],[y])
plt.show()

我收到一个错误 TypeError: cannot convert the series to

【问题讨论】:

  • 我可以提醒您这里的规则之一:“寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:minimal reproducible example。" 在这种情况下,您将创建一些硬编码数据集来重现错误并包含完整的错误回溯,而不仅仅是最后一行。
  • 如果您的问题得到解答,请accept the one that helped the most

标签: python pandas matplotlib typeerror series


【解决方案1】:

使用df.plot,应该更容易。

source_data.set_index("EUGROSHP")["EUGENHTH"].plot(kind='bar', legend=True)
plt.show()

另外,请注意results_1[results_1&gt;0] 会在您的列中为您提供一堆NaNs,您的意思是要过滤单个列吗?

【讨论】:

  • 虽然这实际上并不能解决问题中的问题,但我赞成,因为它鼓励人们考虑直接使用 pandas 绘图功能,从而避免一些常见的陷阱。
  • @ImportanceOfBeingErnest 确实如此,但略有不同。我回报了:)
【解决方案2】:

您将要绘制的系列封装在列表中,plt.bar([x],[y]。这样,您将要求 matplotlib 在位置 x 和高度 y 处精确绘制一个条形图。由于xy不是数值,而是Series本身,这当然是不可能的,会导致错误TypeError: cannot convert the series to &lt;type 'float'&gt;

解决方案很简单,不要将Series放入列表中,而是将它们保留为Series:

plt.bar(x,y)



只是为了向您展示在提出问题时可以使用的最小可验证示例的外观,这里有一个完整的代码:

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import pandas as pd

fig, axes = plt.subplots()
data = pd.DataFrame({"a":np.arange(10)-2,"b":np.random.randn(10)})

results_1 = data[["a","b"]]
results_1_new = results_1[results_1>0]

x=results_1_new['a']
y=results_1_new['b']
plt.bar(x,y)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2019-10-12
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多