Get day of year from a string date in pandas dataf

2020-04-19 05:33发布

问题:

I want to turn my date string into day of year... I try this code..

import pandas as pd
import datetime

data = pd.DataFrame()
data = pd.read_csv(xFilename, sep=",")

and get this DataFrame

Index Date        Tmin    Tmax
0   1950-01-02  -16.508 -2.096
1   1950-01-03  -6.769  0.875
2   1950-01-04  -1.795  8.859
3   1950-01-05  1.995   9.487
4   1950-01-06  -17.738 -9.766

I try this...

convert = lambda x: x.DatetimeIndex.dayofyear
data['Date'].map(convert)

with this error:

AttributeError: 'str' object has no attribute 'DatetimeIndex'

I expect to get new date to match 1950-01-02 = 2, 1950-01-03 = 3... Thank for your help... and sorry Im new on python

回答1:

I think need pass parameter parse_dates to read_csv and then call Series.dt.dayofyear:

data = pd.read_csv(xFilename, parse_dates=["Date"])
data['dayofyear'] = data['Date'].dt.dayofyear