简体   繁体   中英

Plotting Dataframe column - datetime

I have a datetime column with pretty random increments of time, format is:

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

Now I convert it to datetime:

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

Then I want to plot it using matplotlib, but it doesn't work:

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

I've tried converting it to an int, but then I can't figure out how to format it when plotting

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

Any help would be awesome!

I think you can use Series.plot , so first set_index from column time :

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()

图形

Another solution is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM