dlo*_*575 13 python matplotlib pandas
我是 matplotlib 的初学者。我正在尝试使用 matplotlib.pyplot 绘制数据框。问题是,每次我尝试绘制它时,都会出现以下错误:
ValueError: view limit minimum -35738.3640567 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units.
Run Code Online (Sandbox Code Playgroud)
根据错误,日期时间列中似乎有一个非日期时间值,但没有。
我试过使用 pd.to_datetime() 并尝试将时间戳的格式pd.to_datetime(df_google['datetime'], format = '%d/%m/%Y')
更改为但没有任何变化。
这是我尝试使用的代码:
import matplotlib.pyplot as plt
df_google.plot()
plt.show()
Run Code Online (Sandbox Code Playgroud)
df_google 是一个带有列的数据框['datetime','price']
,其中一些值如下:
datetime price
0 2018-05-15 1079.229980
1 2018-05-16 1081.770020
2 2018-05-17 1078.589966
3 2018-05-18 1066.359985
4 2018-05-21 1079.579956
5 2018-05-22 1069.729980
6 2018-05-23 1079.689941
7 2018-05-24 1079.239990
8 2018-05-25 1075.660034
9 2018-05-29 1060.319946
Run Code Online (Sandbox Code Playgroud)
有人可以尝试帮助我理解这种类型的错误吗?当每个值都是日期时间类型值时,为什么它说存在非日期时间值?如何绘制此数据框?
Tre*_*ney 17
'datetime'
列设置为datetime64[ns]
类型:pandas.to_datetime
在转换'datetime'
列,并记住指定列回本身,因为这不是一个就地更新。.
不包含特殊字符并且不与内置属性/方法(例如index
, count
)发生冲突,则可以使用 来访问列名。
df_google.datetime
代替 df_google['datetime']
import pandas as pd
import matplotlib.pyplot as plt
# given the following data
data = {'datetime': ['2018-05-15', '2018-05-16', '2018-05-17', '2018-05-18', '2018-05-21', '2018-05-22', '2018-05-23', '2018-05-24', '2018-05-25', '2018-05-29'],
'price': [1079.22998, 1081.77002, 1078.589966, 1066.359985, 1079.579956, 1069.72998, 1079.689941, 1079.23999, 1075.660034, 1060.319946]}
df_google = pd.DataFrame(data)
# convert the datetime column to a datetime type and assign it back to the column
df_google.datetime = pd.to_datetime(df_google.datetime)
# display(df_google.head())
datetime price
0 2018-05-15 1079.229980
1 2018-05-16 1081.770020
2 2018-05-17 1078.589966
3 2018-05-18 1066.359985
4 2018-05-21 1079.579956
5 2018-05-22 1069.729980
6 2018-05-23 1079.689941
7 2018-05-24 1079.239990
8 2018-05-25 1075.660034
9 2018-05-29 1060.319946
Run Code Online (Sandbox Code Playgroud)
'datetime'
列是datetime64[ns]
Dtype:print(df_google.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 datetime 10 non-null datetime64[ns]
1 price 10 non-null float64
dtypes: datetime64[ns](1), float64(1)
memory usage: 288.0 bytes
Run Code Online (Sandbox Code Playgroud)
df_google.plot(x='datetime')
plt.show()
Run Code Online (Sandbox Code Playgroud)
df.plot()
可以很好地查看数据。