简体   繁体   中英

Pandas DataFrame index - month and day only

I'd like to have a DataFrame with a DatetimeIndex , but I only want the months and days; not years. I'd like it to look like the following:

(index)  (values)
01-01    56.2
01-02    59.6
...
01-31    62.3
02-01    61.6
...
12-31    44.0

I've tried creating a date_range but this seems to require the year input, so I can't seem to figure out how to achieve the above.

you can do it this way:

In [78]: df = pd.DataFrame({'val':np.random.rand(10)}, index=pd.date_range('2000-01-01', freq='10D', periods=10))

In [79]: df
Out[79]:
                 val
2000-01-01  0.422023
2000-01-11  0.215800
2000-01-21  0.186017
2000-01-31  0.804285
2000-02-10  0.014004
2000-02-20  0.296644
2000-03-01  0.048683
2000-03-11  0.239037
2000-03-21  0.129382
2000-03-31  0.963110

In [80]: df.index.dtype_str
Out[80]: 'datetime64[ns]'

In [81]: df.index.dtype
Out[81]: dtype('<M8[ns]')

In [82]: df.index = df.index.strftime('%m-%d')

In [83]: df
Out[83]:
            val
01-01  0.422023
01-11  0.215800
01-21  0.186017
01-31  0.804285
02-10  0.014004
02-20  0.296644
03-01  0.048683
03-11  0.239037
03-21  0.129382
03-31  0.963110

In [84]: df.index.dtype_str
Out[84]: 'object'

In [85]: df.index.dtype
Out[85]: dtype('O')

NOTE: the index dtype is a string (object) now

PS of course you can do it in one step if you nedd:

In [86]: pd.date_range('2000-01-01', freq='10D', periods=5).strftime('%m-%d')
Out[86]:
array(['01-01', '01-11', '01-21', '01-31', '02-10'],
      dtype='<U5')

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