【发布时间】:2019-11-03 07:30:34
【问题描述】:
我有一个数据框df,如下所示,其中存在Date 字段。我正在使用pd.read_excel() 方法从excel 中读取此内容。
Company Code Trxn_date Company Name Type
20040 2019-05-11 00:00:00 ABC Series A #<--the date is in `datetime` object only.
20034 2019-04-26 00:00:00 XYZ Series A
20033 "5/15/2018\n23/4/2019" PQR "Series A
Series B" # <-- In same row.
20040 2019-06-05 00:00:00 ABC Series B
20056 8/16/2019 MNO Series B
如您所见,对于20033,Trxn_date 中有两个条目,相隔\n。 Type 字段也是如此。因此,如果我申请pd.to_datetime(df['Trxn_date']),我会得到一个明显的错误TypeError: invalid string coercion to datetime。我不想coerce 选项。
请注意,除了20033 和20056 之外,所有日期都会被pandas 自动转换为datetime 对象。
我想得到df,如下所示。
Company Code Trxn_date Company Name Type
20040 2019-05-11 ABC Series A
20034 2019-04-26 XYZ Series A
20033 2019-04-23 PQR Series B #<--Only the last date string is picked up and converted to datetime.
20040 2019-06-05 ABC Series B
20056 2019-08-16 MNO Series B #<--The date format is changed to `yyyy-mm-dd`.
我无法获得任何线索来实现上述相同。对于20056,我可以使用pd.to_datetime(df['Trxn_date'],errors='coerce').apply(lambda x : x.strftime('%Y-%m-%d') if pd.notnull(x) else ' ')。此操作在Trxn_date 字段中为20033 创建一个空白。
任何人都可以对此提供任何见解吗?可能我必须编写一个函数然后使用lambda 吗?
【问题讨论】: