使用pandas

时间:2016-11-23 17:24:30

标签: python python-2.7 csv pandas

我正在尝试将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')

3 个答案:

答案 0 :(得分:1)

您可以这样做:

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

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

答案 1 :(得分:0)

您可以使用pandas.Series.str.cat函数。

以下代码为您提供了一个基本概念:

>>> Series(['a', 'b', 'c']).str.cat(['A', 'B', 'C'], sep=',')
0    a,A
1    b,B
2    c,C
dtype: object

有关详细信息,请查看:

http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.str.cat.html

希望这能解决你的问题...

答案 2 :(得分:0)

我终于得到了一个解决方案,我在日期列之前删除了问号,并将to_datetime()应用于数据框的列

df['From'] = df['From'].map(lambda x: str(x)[1:])
df['FromTime'] = pd.to_datetime(df['Date'].str.cat(df['From'], sep=" "),format='%Y-%m-%d %H:%M:%S', errors='coerce')