n8-*_*gr8 4 datetime python-3.x pandas
我需要在dates数据帧(https://pastebin.com/kNqLtUWu)内执行验证,检查 a 是否date有效。如果date无效(即pd.to_datetime无法解析 - 0107-01-06,例如),我需要Fail用Yes.
我对包含日期的列进行子集化,并能够识别包含无效日期的列并将它们添加到字典中,但尚未弄清楚如何返回特定行。
我对其他方法持开放态度,但我需要使用pandas并最终使用失败列来指示行,我计划在该行上过滤最终数据帧(一个数据帧包含带有错误日期的行,另一个数据帧不包含错误)。
完整代码请参见pastebin链接
# insert empty Fail column to identify date errors
df.insert(loc=0, column='Fail', value="")
# replace all blanks with np.NaN
df.replace(r"^s*$", np.nan, regex=True, inplace = True)
# get list of date columns
cols = list(df)
date_cols = cols[2:]
# create empty dict
dfs = {}
# iterate over date columns to identify which columns contain invalid dates & add to dfs
for col in df[date_cols]:
try:
df[col] = df[col].apply(pd.to_datetime, errors='raise')
except:
print("%s column contains invalid date" % col)
dfs[col] = df[col]
Run Code Online (Sandbox Code Playgroud)
coerce您所描述的问题可以通过一点逻辑来解决:
# original non_null
notnull = df[col].notnull()
# where to_datetime fails
not_datetime = pd.to_datetime(df[col], errors='coerce').isna()
not_datetime = not_datetime & notnull
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3820 次 |
| 最近记录: |