Skip to main content
 首页 » 编程设计

python之使用 Pandas 组合列

2025年02月15日14zhwl

我正在尝试合并 csv 文件的日期和时间列,并使用 pandas 将它们转换为时间戳。

这是读入数据框时我的 csv 文件的示例

Dataframe after reading

Id     Station        Month       Parameter    Date        From       To 
1.0    ANANDVIHAR     Dec         ?PM2.5       2015-12-01  ?00:00:00  ?00:59:00 

以下代码:-

df['DateTime'] = df.apply(lambda row: datetime.datetime.strptime(row['Date']+ ':' + row['From'], '%Y.%m.%d:%H:%M:%S'), axis=1) 

出现以下错误:-

Traceback (most recent call last): 
 
  File "project101.py", line 36, in <module> 
    df['DateTime'] = df.apply(lambda row: datetime.datetime.strptime(row['Date']+ ':' + row['From'], '%Y.%m.%d:%H:%M:%S'), axis=1) 
 
  File "c:\Python27\lib\site-packages\pandas\core\frame.py", line 4133, in apply 
    return self._apply_standard(f, axis, reduce=reduce) 
 
 File "c:\Python27\lib\site-packages\pandas\core\frame.py", line 4229, in _apply_standard 
    results[i] = func(v) 
 
  File "project101.py", line 36, in <lambda> 
    df['DateTime'] = df.apply(lambda row: datetime.datetime.strptime(row['Date']+ ':' + row['From'], '%Y.%m.%d:%H:%M:%S'), axis=1) 
 
  File "c:\Python27\lib\_strptime.py", line 332, in _strptime 
    (data_string, format)) 
 
ValueError: ("time data '2015-12-01:\\xa000:00:00' does not match format '%Y.%m.%d:%H:%M:%S'", u'occurred at index 0') 

请您参考如下方法:

你可以简单地做:

df['DateTime'] = pd.to_datetime(df['Date'].str.cat(df['From'], sep=" "), 
                                format='%Y-%m-%d \\xa%H:%M:%S', errors='coerce') 

格式说明符中的 '\\xa' 将处理问号。这些标记用于误解的文字,可能看起来像 '\\xa'