Hong
Hong

Reputation: 263

python how to convert one column in dataframe to date tye and plot

I have one dataframe df as below:

df = pd.DataFrame({'date': [20121231,20130102, 20130105, 20130106, 20130107, 20130108],'price': [25, 163, 235, 36, 40, 82]})

How to make df['date'] as date type and make 'price' as y-label and 'date' as x-label?

Thanks a lot.

Upvotes: 1

Views: 158

Answers (3)

With pandas you can directly convert the date column to datetime type. And then you can plot with matplotlib. Take a look at this answer and also this one.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

df = pd.DataFrame(
    {'date': [20121231, 20130102, 20130105, 20130106, 20130107, 20130108],
    'price': [25, 163, 235, 36, 40, 82]
})

fig, ax = plt.subplots()

# Date plot with matplotlib
ax.plot_date(
    pd.to_datetime(df["date"], format="%Y%m%d"),
    df["price"],
    'v-'
)

# Days and months and the horizontal locators
ax.xaxis.set_minor_locator(dates.DayLocator())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))

ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
plt.tight_layout()
plt.show()

Result:

enter image description here

Upvotes: 1

Chandu
Chandu

Reputation: 2129

import pandas as pd
%matplotlib inline
df = pd.DataFrame({'date': [20121231,20130102, 20130105, 20130106, 20130107, 
                            20130108],'price': [25, 163, 235, 36, 40, 82]})
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')

df.plot(x='date', y='price')

Upvotes: 1

jezrael
jezrael

Reputation: 862406

Use to_datetime with parameter format, check http://strftime.org/:

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
print (df)
        date  price
0 2012-12-31     25
1 2013-01-02    163
2 2013-01-05    235
3 2013-01-06     36
4 2013-01-07     40
5 2013-01-08     82

And then plot:

df.plot(x='date', y='price')

Upvotes: 3

Related Questions