【问题标题】:Plotting Dataframe column - datetime绘制数据框列 - 日期时间
【发布时间】:2016-11-11 11:12:42
【问题描述】:

我有一个带有相当随机时间增量的日期时间列,格式为:

time
2016-07-08 11:29:30
2016-07-08 11:30:02

现在我将其转换为日期时间:

df['time2'] = pd.to_datetime(df['time'])

然后我想用matplotlib来绘制它,但是它不起作用:

plt.plot(df.['time'],df['y'])

我尝试将其转换为 int,但是在绘图时我无法弄清楚如何格式化它

 df['time_int'] = df['time2'].astype(np.int64)

任何帮助都会很棒!

【问题讨论】:

  • 其余数据是什么样的?您可能首先需要resample 您的数据。

标签: python datetime pandas matplotlib dataframe


【解决方案1】:

我认为你可以使用Series.plot,所以首先来自time列的set_index:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'y': {0: 1, 1: 2, 2: 4}, 
                   'time': {0: '2016-07-08 11:29:30', 1: '2016-07-08 11:30:02', 2: '2016-07-08 11:31:52'}})

print (df)
                  time  y
0  2016-07-08 11:29:30  1
1  2016-07-08 11:30:02  2
2  2016-07-08 11:31:52  4

df['time'] = pd.to_datetime(df.time)

print (df.set_index('time').y)
time
2016-07-08 11:29:30    1
2016-07-08 11:30:02    2
2016-07-08 11:31:52    4
Name: y, dtype: int64

df.set_index('time').y.plot()
plt.show()

另一种解决方案是:

df['time'] = pd.to_datetime(df.time)
df.plot(x='time', y='y')
plt.show()

【讨论】:

  • 效果很好!感谢你的帮助。我缺少的部分是 set_index 语句。
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2020-07-28
  • 2021-03-20
相关资源
最近更新 更多