python - csv文件中多列的python pandas parse_dates
问题描述
我正在使用 Python pandas 来比较两个 csv 文件,但是在具有 5 个日期列的 csv 文件中,我在 read_csv 方法中使用了 parse_date=['dateofbirth','lastupdates','dateofjoin','dateofresign,'endoftrade'] 但是它只是解析 dateofbirth 而不是 csv 文件中的所有列。
代码:
csv_pandas=pd.read_csv("path of the csv file",parse_date=['dateofbirth','lastupdates','dateofjoin','dateofresign,'endoftrade'])
print(csv_pandas)
CSV 文件:
dateofbirth lastupdates dateofjoin dateofresign
05/06/2021 00:00:00PM 12/13/2021 12:00:00PM 12/13/2021 12:00:00PM 12/13/2021 12:00:00PM
column non-null count Dtype
------ ------------- ------
dateofbirth non-null object
dateofbirth non-null datetime64[ns]
dateofbirth non-null datetime64[ns]
dateofbirth non-null datetime64[ns]
我只能转换对象 Dtype 列,剩余的 datetime64[ns] 不解析
大约我有 160 个 csv 文件,每个 csv 文件都有不同的列名,任何人都可以建议
解决方案
- 您有两种需要不同
strptime()
格式说明的日期格式。 - 并非您尝试转换的所有列都存在于数据框中,因此测试该列存在于作为 ** kwargs传递的dict理解中
assign()
csv_pandas = csv_pandas.assign(
**{
c: pd.to_datetime(csv_pandas[c], format="%Y-%m-%d %H:%M:%S:%f", errors="ignore")
for c in parse_date
if c in csv_pandas.select_dtypes("object").columns
}
).pipe(
lambda d: d.assign(
**{
c: pd.to_datetime(d[c], format="%m/%d/%Y %H:%M:%S%p", errors="ignore")
for c in parse_date
if c in d.select_dtypes("object").columns
}
)
)
输出
csv_pandas.dtypes
dateofbirth datetime64[ns]
lastupdates datetime64[ns]
dateofjoin datetime64[ns]
dateofresign datetime64[ns]
dtype: object
推荐阅读
- docker - 将容器存储在路径中
- javascript - 使用 Cloud Function 在 Firestore 上写入数据突然失败
- c - Apple Hypervisor 在 MacOS Big Sur beta 11.0.1 上完全崩溃
- file - Typo3 Powermail 文件上传 上传前调整文件大小
- c++ - Robocopy - 如果我在它完成之前停止它会产生损坏的文件吗?
- sql - 检查字符串是否存在子字符串
- python - 如何检查 3 列是否相同,如果值相同,如何添加一个新列?
- r - 如何使用闪亮在交互式 html 报告中显示两个数据输出
- javascript - 电子:NodeJS 'net' 模块返回空对象
- r - 为什么随机效应估计器不正确