ValueError Traceback (most recent call last) Cell In[1], line 3 1 import pandas as pd 2 df = pd.read_csv('beijing_wangjing_125.txt', sep=',') ----> 3 df['daily_10min'] = pd.to_datetime(df['daily_10min'], format='%Y%m%d%H') 4 df.to_csv('beijing_wangjing_125_new.csv', index=False) File ~\anaconda3\lib\site-packages\pandas\core\tools\datetimes.py:1068, in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, infer_datetime_format, origin, cache) 1066 result = arg.map(cache_array) 1067 else: -> 1068 values = convert_listlike(arg._values, format) 1069 result = arg._constructor(values, index=arg.index, name=arg.name) 1070 elif isinstance(arg, (ABCDataFrame, abc.MutableMapping)): File ~\anaconda3\lib\site-packages\pandas\core\tools\datetimes.py:430, in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact) 427 format = None 429 if format is not None: --> 430 res = _to_datetime_with_format( 431 arg, orig_arg, name, tz, format, exact, errors, infer_datetime_format 432 ) 433 if res is not None: 434 return res File ~\anaconda3\lib\site-packages\pandas\core\tools\datetimes.py:538, in _to_datetime_with_format(arg, orig_arg, name, tz, fmt, exact, errors, infer_datetime_format) 535 return _box_as_indexlike(result, utc=utc, name=name) 537 # fallback --> 538 res = _array_strptime_with_fallback( 539 arg, name, tz, fmt, exact, errors, infer_datetime_format 540 ) 541 return res File ~\anaconda3\lib\site-packages\pandas\core\tools\datetimes.py:473, in _array_strptime_with_fallback(arg, name, tz, fmt, exact, errors, infer_datetime_format) 470 utc = tz == "utc" 472 try: --> 473 result, timezones = array_strptime(arg, fmt, exact=exact, errors=errors) 474 except OutOfBoundsDatetime: 475 if errors == "raise": File ~\anaconda3\lib\site-packages\pandas\_lib
时间: 2024-02-19 14:57:23 浏览: 180
pandas 强制类型转换 df.astype实例
根据错误提示,可能是因为数据中存在某些值无法用指定的格式`%Y%m%d%H`转换为日期时间类型。您可以尝试使用`errors='coerce'`参数来处理这些无法转换的值,将其转换为`NaT`(不是时间):
```python
df['daily_10min'] = pd.to_datetime(df['daily_10min'], format='%Y%m%d%H', errors='coerce')
```
如果您希望将无法转换的行删除,则可以使用`dropna()`函数:
```python
df.dropna(subset=['daily_10min'], inplace=True)
```
完整代码如下:
```python
import pandas as pd
df = pd.read_csv('beijing_wangjing_125.txt', sep=',')
df['daily_10min'] = pd.to_datetime(df['daily_10min'], format='%Y%m%d%H', errors='coerce')
df.dropna(subset=['daily_10min'], inplace=True)
df.to_csv('beijing_wangjing_125_new.csv', index=False)
```
阅读全文