我在csv文件中有一些数据,其中有一些MM / DD / YYYY格式的条目和一些DD-MM-YYYY格式的条目。我想阅读这一列条目并将其存储为pandas数据框中的新列?我该怎么做?
示例:
Entry Sampling Date
1 01-10-2004
2 01-13-2004
3 16/1/2004
我想转换前两行'日期格式为第三行中的格式。
答案 0 :(得分:2)
使用datetime
模块,定义一个功能,然后将其应用到您的专栏
import datetime.datetime
def read_date(string):
if '/' in entry:
date = datetime.datetime.strptime(string,'%m/%d/%Y')
elif '-' in entry:
date = datetime.datetime.strptime(string, '%d-%m-%Y')
return date
# If df is your dataframe
df['newdate'] = df['Sampling Date'].apply(read_date)