I have a multi-index series like this:
Year Month
2012 1 444
2 222
3 333
4 1101
which I want to turn into:
Date Value
2012-01 444
2012-02 222
2012-03 333
2012-04 1101
to plot a line.
I have tried both series.unstack(level=0)
and series.unstack(level=1)
, but this creates a matrix
In[1]: series.unstack(level=0)
Out[1]:
Year 2012 2013 2014 2015 2016 2017 2018
Month
1 444 ... ... ... ... ... ...
2 222 ... ... ... ... ... ...
3 333 ... ... ... ... ... ...
4 1101 ... ... ... ... ... ...
What am I missing?
Use Index.to_frame
with to_datetime
working if also added Day
column, and reasign back:
s.index = pd.to_datetime(s.index.to_frame().assign(Day=1))
print (s)
2012-01-01 444
2012-02-01 222
2012-03-01 333
2012-04-01 1101
Name: a, dtype: int64
For one column DataFrame
use Series.to_frame
:
df1 = s.to_frame('Value')
print (df1)
Value
2012-01-01 444
2012-02-01 222
2012-03-01 333
2012-04-01 1101
If need PeriodIndex
add Series.dt.to_period
:
s.index = pd.to_datetime(s.index.to_frame().assign(Day=1)).dt.to_period('m')
print (s)
2012-01 444
2012-02 222
2012-03 333
2012-04 1101
Freq: M, Name: a, dtype: int64
df2 = s.to_frame('Value')
print (df2)
Value
2012-01 444
2012-02 222
2012-03 333
2012-04 1101
idx = pd.PeriodIndex(
year=s.index.get_level_values(0).tolist(),
month=s.index.get_level_values(1).tolist(),
freq='M',
name='Date'
)
s2 = pd.Series(s.values, index=idx, name=s.name)
s2.plot()
You could also use a list comprehension with f-strings to create a DatetimeIndex.
idx = pd.to_datetime([f'{year}-{month}' for year, month in s.index])
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.