gpt4 book ai didi

python - 试图绘制的 Pandas 类型错误

转载 作者:IT老高 更新时间:2023-10-28 21:10:12 25 4
gpt4 key购买 nike

我正在尝试基于 Pandas 数据框创建基本散点图。但是当我调用分散例程时,我收到一个错误“TypeError:无效类型提升”。重现问题的示例代码如下所示:

t1 = pd.to_datetime('2015-11-01 00:00:00')
t2 = pd.to_datetime('2015-11-02 00:00:00')

Time = pd.Series([t1, t2])
r = pd.Series([-1, 1])

df = pd.DataFrame({'Time': Time, 'Value': r})
print(df)

print(type(df.Time))
print(type(df.Time[0]))

fig = plt.figure(figsize=(x_size,y_size))
ax = fig.add_subplot(111)
ax.scatter(df.Time, y=df.Value, marker='o')

结果输出是

        Time  Value
0 2015-11-01 -1
1 2015-11-02 1
<class 'pandas.core.series.Series'>
<class 'pandas.tslib.Timestamp'>

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-285-f4ed0443bf4d> in <module>()
15 fig = plt.figure(figsize=(x_size,y_size))
16 ax = fig.add_subplot(111)
---> 17 ax.scatter(df.Time, y=df.Value, marker='o')

C:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, **kwargs)
3635 edgecolors = 'face'
3636
-> 3637 offsets = np.dstack((x, y))
3638
3639 collection = mcoll.PathCollection(

C:\Anaconda3\lib\site-packages\numpy\lib\shape_base.py in dstack(tup)
365
366 """
--> 367 return _nx.concatenate([atleast_3d(_m) for _m in tup], 2)
368
369 def _replace_zero_by_x_arrays(sub_arys):

TypeError: invalid type promotion

四处搜索我发现了一个类似的帖子Pandas Series TypeError and ValueError when using datetime这表明该错误是由系列中有多种数据类型引起的。但这似乎不是我的示例中的问题,正如我打印的类型信息所证明的那样。

请注意,如果我停止使用 pandas 日期时间对象并将“时间”设置为 float ,则可以正常工作,例如

t1 = 1.1 #
t2 = 1.2

Time = pd.Series([t1, t2])
r = pd.Series([-1, 1])

df = pd.DataFrame({'Time': Time, 'Value': r})
print(df)

print(type(df.Time))
print(type(df.Time[0]))

fig = plt.figure(figsize=(x_size,y_size))
ax = fig.add_subplot(111)
ax.scatter(df.Time, y=df.Value, marker='o')

有输出

   Time  Value
0 1.1 -1
1 1.2 1
<class 'pandas.core.series.Series'>
<class 'numpy.float64'>

图表看起来还不错。我不知道为什么使用日期时间会导致无效类型提升错误?我正在使用 Python 3.4.3 和 pandas 0.16.2。

最佳答案

感谢@martinvseticka。根据您指出的 numpy 代码,我认为您的评估是正确的。我能够进一步简化您的调整(并添加了第三个样本点)以获得

t1 = pd.to_datetime('2015-11-01 00:00:00')
t2 = pd.to_datetime('2015-11-02 00:00:00')
t3 = pd.to_datetime('2015-11-03 00:00:00')

Time = pd.Series([t1, t2, t3])
r = pd.Series([-1, 1, 0.5])

df = pd.DataFrame({'Time': Time, 'Value': r})

fig = plt.figure(figsize=(x_size,y_size))
ax = fig.add_subplot(111)
ax.plot_date(x=df.Time, y=df.Value, marker='o')

关键似乎是调用“plot_date”而不是“plot”。这似乎告诉 mapplotlib 不要尝试连接数组。

关于python - 试图绘制的 Pandas 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com