【问题标题】:Combining columns using pandas使用 pandas 组合列
【发布时间】:2017-04-07 20:00:28
【问题描述】:

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

【问题讨论】:

  • 你的问题看起来一团糟。请使用正确的格式。

标签: python python-2.7 csv pandas


【解决方案1】:

我终于得到了一个解决方案,我去掉了日期列之前的问号,并将 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', 错误='强制')

【讨论】:

    【解决方案2】:

    你可以这样做:

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

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

    【讨论】:

    • 我尝试了解决方案,但 DateTime 列中的所有值都是“NaT”
    • 谢谢kartik 我终于找到了解决方案
    【解决方案3】:

    您可以使用 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

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

    【讨论】:

    • 你能看到打印出来的数据框的图像吗?日期的 From 和 To 列在数据前包含问号。我怎样才能删除它们
    • 感谢 sansingh 提供的 pandas 参考资料
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2019-02-15
    • 2013-08-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多