[英]Pandas - converting dates to datetime, day-month-year to year month day fails with parse dates
I have a dataframe of patients and operations, with 6 date columns.我有一个包含 6 个日期列的患者和手术数据框。 The dates are in the format of day-month-year.
日期采用日-月-年的格式。 To get the hospital length of stay I need to subtract the admission date [ADMIDATE] from the discharge date (DISDATE).
要获得住院时间,我需要从出院日期 (DISDATE) 中减去入院日期 [ADMIDATE]。 I want to change the date columns to datetime columns.
我想将日期列更改为日期时间列。
As an example举个例子
ADMIDATE DISDATE
0 06/06/2014 07/06/2014
1 23/06/2014 23/06/2014
if use如果使用
pd.read_csv('/Users/.......csv', parse_dates=['ADMIDATE', 'DISDATE'])
I get我得到
ADMIDATE DISDATE
0 2014-06-06 2014-07-06
1 2014-06-23 2014-06-23
and the 7th June is turned into the 6th July.(DISDATE , row[0] ) If I use the more strict 6 月 7 日变成了 7 月 6 日。(DISDATE , row[0] ) 如果我使用更严格的
for col in ['ADMIDATE', 'DISDATE']:
df[col] = pd.to_datetime(df[col], format='%d/%m/%Y')
it works有用
ADMIDATE DISDATE
0 2014-06-06 2014-06-07
1 2014-06-23 2014-06-23
But it won't accept the many empty rows where for instance the patient hasn't yet been discharged at the time of data collection.但它不会接受许多空行,例如在数据收集时患者尚未出院。 I can format the date columns in excel to get the csv into year-month-day format and then use parse dates and it works correctly but I would like to know what I can do with
to_datetime
.我可以在 excel 中格式化日期列以将 csv 转换为年-月-日格式,然后使用解析日期并且它可以正常工作,但我想知道我可以用
to_datetime
做什么。
dayfirst
This argument forces the parser to interpret the day first此参数强制解析器首先解释这一天
df.apply(pd.to_datetime, dayfirst=True)
ADMIDATE DISDATE
0 2014-06-06 2014-06-07
1 2014-06-23 2014-06-23
To specify columns:要指定列:
df[['ADMIDATE', 'DISDATE']].apply(pd.to_datetime, dayfirst=True)
ADMIDATE DISDATE
0 2014-06-06 2014-06-07
1 2014-06-23 2014-06-23
error='coerce'
To accommodate missing data:为了适应缺失的数据:
df[['ADMIDATE', 'DISDATE']].apply(
pd.to_datetime, dayfirst=True, errors='coerce'
)
ADMIDATE DISDATE
0 2014-06-06 2014-06-07
1 2014-06-23 2014-06-23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.