且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将datetime字符串转换为pandas数据框中的Day,Month,Year的新列

更新时间:2022-03-19 04:29:22

只需用-T分隔时间,前三个元素应对应于年,月和日列,并将其与其他列连接两列将满足您的需求:

Just split the time with - or T and the first three elements should correspond to the year, month and day column, concatenate it with the other two columns will get what you need:

pd.concat([df.drop('time', axis = 1), 
          (df.time.str.split("-|T").str[:3].apply(pd.Series)
          .rename(columns={0:'year', 1:'month', 2:'day'}))], axis = 1)

一种类似于@nlassaux的方法的替代方法是:

An alternative close to @nlassaux's approach would be:

df['time'] = pd.to_datetime(df['time'])   
df['year'] = df.time.dt.year
df['month'] = df.time.dt.month
df['day'] = df.time.dt.day
df.drop('time', axis=1, inplace=True)