【发布时间】:2020-08-13 10:40:09
【问题描述】:
我想转换一个包含日期字符串的数据框列。但在某些情况下,由于某些条件,日期字符串可能为空。因此,我只想将该列中的所有其他行转换为日期时间格式,但该特定列中可能为空白的行除外。有可能吗?
到目前为止我已经尝试过:
选项1:
df['etime'] = pd.to_datetime(df['etime'],errors='ignore').dt.strftime('%Y-%m-%d %H:%M')
选项 2:
for ind in df.index:
if (df['etime'].str.len()[ind] == 0) :
df.loc[ind, 'etime'] = "----"
else:
df.loc[ind, 'etime'] = <need to convert this row to datetime>
请提供您的建议。
数据框示例:
data = pd.DataFrame({
'day' : [15, 17, 20, 14, 25],
'etime': ["20200811235205", "", "20200811215205", "20200811225205", "20200811235203"]
})
【问题讨论】:
-
在数据框中显示数据
-
pd.to_datetime(df['etime'],errors='ignore')是做什么的? -
@Manakin -> 它只是在适用的行上转换为日期时间,但不进行格式化 ''%Y-%m-%d %H:%M''
标签: python python-3.x pandas dataframe python-datetime