2016-11-23 56 views
2

我想將csv文件的日期和時間列組合起來,並將它們轉換爲使用熊貓的時間戳。使用熊貓組合列使用

這裏是我的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') 
+0

你的問題看起來都搞砸了。請使用正確的格式。 – burhan

回答

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'

+0

我試過解決方案,但DateTime列中的所有值都是「NaT」 – Niteesh

+0

嘗試使用格式進行播放,直到您找到正確的答案。 – Kartik

+0

謝謝kartik我終於得到了解決方案 – Niteesh

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

希望這能解決你的問題......

+0

你能看到打印數據幀的圖像嗎?日期的From和To列包含數據前的問號。我如何刪除它們 – Niteesh

+0

感謝sansingh熊貓參考幫助 – Niteesh

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')