简体   繁体   中英

Convert pandas column 'day of year' to datetime (%m-%d)?

Suppose I have a Pandas DataFrame with a column which is the number of the day of the year (1 to 365). I would like to get a new column which is a datetime format (or any format which can be plotted as date index) which has only day and month (NO YEAR) value? That said the format of strftime would be %d-%m.

So far I have managed to produce with strftime from a day numer 1 -> 01-01, the problem is that it is now a strip which is not useful for plotting my data...

Any ideas how to get around the Year value?

Here is an example dataframe with a Date column:

   Date     Open     High     Low    Close  Adj Close    Volume
0     1  4.06250  4.12500  3.8750  3.90625   3.093209   7048800
1     2  3.84375  3.96875  3.5000  3.62500   2.870497  12864000
2     3  3.50000  4.25000  3.5000  4.12500   3.266428   9526400
3     4  4.06250  4.68750  4.0625  4.50000   3.563378   5693600
4     5  4.40625  4.65625  4.1250  4.21875   3.340666  30480000

You can then parse the Date using pd.to_datetime() , then reformat the dates using strftime() :

df['Date'] = pd.to_datetime(df['Date'], format='%j').dt.strftime('%m-%d')

Gives:

    Date     Open     High     Low    Close  Adj Close    Volume
0  01-01  4.06250  4.12500  3.8750  3.90625   3.093209   7048800
1  01-02  3.84375  3.96875  3.5000  3.62500   2.870497  12864000
2  01-03  3.50000  4.25000  3.5000  4.12500   3.266428   9526400
3  01-04  4.06250  4.68750  4.0625  4.50000   3.563378   5693600
4  01-05  4.40625  4.65625  4.1250  4.21875   3.340666  30480000

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