简体   繁体   中英

Tuple to datetime

I have a dataframe tha tI have grouped by month and day and looks like this

     Value
1  2 22
  10 30
  15 5
2  8 12
  20 15
3  5 20

The ifrst index indicates the month and the second index refers the day.

I would like to plot the column "Value" on a plot where the need to be day-month in this format, eg 2-Jan

When I cam calling df.index.tolist() I am getting a tuple of the indexes (1,2),(1,10) etc but I do not know how can I convert these to a daytime object.Thanks

You can use rename_axis with reset_index and assign for create df1 .

Then to_datetime and format by strftime , output is assigned back to index :

df1 = df.rename_axis(['month','day']).reset_index().assign(year=2000)
print (df1)
   month  day  Value  year
0      1    2     22  2000
1      1   10     30  2000
2      1   15      5  2000
3      2    8     12  2000
4      2   20     15  2000
5      3    5     20  2000

df.index = pd.to_datetime(df1[['day','month','year']]).dt.strftime('%d-%b')
print (df)
        Value
02-Jan     22
10-Jan     30
15-Jan      5
08-Feb     12
20-Feb     15
05-Mar     20

Another solution:

idx = df.index.map(lambda x: '-'.join((str(x[0]), str(x[1]), '2000')))
print (idx)
['1-2-2000' '1-10-2000' '1-15-2000' '2-8-2000' '2-20-2000' '3-5-2000']

df.index = pd.to_datetime(idx).strftime('%d-%b')
print (df)
        Value
02-Jan     22
10-Jan     30
15-Jan      5
08-Feb     12
20-Feb     15
05-Mar     20

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