样本数据帧:
id col1 col2
0 Bob 2018-11-29 TO 2018-11-30 2018-12-01 TO 2018-12-31
1 James 2018-10-19 TO 2018-10-31 NaT
2 Jane 2018-04-05 TO 2018-07-12 2018-11-29 TO 2018-11-30
我有两列显示日期范围为:
"2018-11-29 TO 2018-11-30"
我已经成功地将第一列中的每个日期提取到两个新列中,如下所示:
def my_func(data):
dates = data.split(" TO ")
dt1 = pd.to_datetime(dates[0].strip(), format="%Y-%m-%d")
dt2 = pd.to_datetime(dates[1].strip(), format="%Y-%m-%d")
return (dt1, dt2)
df[["new_col_1", "new_col_2"]] = df.apply(lambda row: pd.Series(my_func(row["col1"])), axis=1)
这在"col1"中运行良好,因为每一行都有一个值。然而,在"col2"中,并不是每一行都有一个值。我希望它跳过那些行,但它不起作用。我试着在lambda语句中使用带有条件逻辑的pd.notnull()
,但我认为pd.Series()
正在放弃它,它一直试图传递值,我一直得到:
AttributeError: ("'float' object has no attribute 'split'", 'occurred at index 0')
但是列("col1"one_answers"col2"(的实际dtype
是object
(字符串(,而不是浮点,所以我不确定它为什么会出现这个错误。
如何修改它,使其工作,但跳过该列没有值的行?
不需要自定义功能
#df=pd.DataFrame({'string':["2018-11-29 TO 2018-11-30","2018-11-29 TO 2018-11-30","2018-11-29 TO 2018-11-30"]})
df.string.str.split(' TO ',expand=True).apply(pd.to_datetime)
Out[571]:
0 1
0 2018-11-29 2018-11-30
1 2018-11-29 2018-11-30
2 2018-11-29 2018-11-30
#pd.concat([df,df.string.str.split(' TO ',expand=True).apply(pd.to_datetime)],axis=1)
更新
df1=df.col1.str.split('TO',expand=True).apply(pd.to_datetime,errors='coerce')
df1.columns=['col1_1', 'col1_2']
df2=df.col2.str.split('TO',expand=True).apply(pd.to_datetime,errors='coerce')
df2.columns=['col2_1', 'col2_2']
pd.concat([df,df1,df2],1)
Out[578]:
id col1 ... 0 1
0 Bob 2018-11-29TO2018-11-30 ... 2018-12-01 2018-12-31
1 James 2018-10-19TO2018-10-31 ... NaT NaT
2 Jane 2018-04-05TO2018-07-12 ... 2018-11-29 2018-11-30
[3 rows x 7 columns]