合并数据时我不断遇到错误:
record_id month day year sex
1 7 17 1977 M
2 7 15 1979 M
3 7 26 1978 F
4 7 16 1973 M
我尝试了不同的方法将月份、日期和年份合并到一列中:
1. surveys_df['date'] = surveys_df['month'].astype(str) + surveys_df['day'] + surveys_df['year']
2. surveys_df['Date'] = pd.to_datetime(surveys_df[['month', 'day', 'year']])
3. r= pd.to_datetime(surveys_df[['year', 'month', 'day']])
4. surveys_df['date'] = pd.to_datetime(surveys_df[['day','month','year']])
我得到的错误:
ValueError: cannot assemble the datetimes: day is out of range for day
我知道我可以通过使用error='coerce'来强制它,但我不想使用这种方法。
最佳答案
pd.to_datetime(df[['year', 'month', 'day']])
0 1977-07-17
1 1979-07-15
2 1978-07-26
3 1973-07-16
dtype: datetime64[ns]
如果您想要 NaTify 存在无效组合,请添加 errors='coerce'
参数。
关于python - 使用 pandas 将年、月、日列合并为单个日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358779/