2013-06-25 20 views
3

謝謝大家提前爲您準備好時間。我在格式中有一些空格分隔的文本文件;使用Python的熊貓從TXT文件中解析DD MM YY HH MM SS列

29 04 13 18 15 00 7.667 
    29 04 13 18 30 00 7.000 
    29 04 13 18 45 00 7.000 
    29 04 13 19 00 00 7.333 
    29 04 13 19 15 00 7.000 

格式爲DD MM YY HH MM SS和我的結果值。我正在嘗試使用Python的熊貓來讀取txt文件。在發佈這個問題之前,我已經嘗試過對此進行相當多的研究,所以希望我不會涉及踐踏的理由。

基於摸索與研究,我想出了:

import pandas as pd 
    from cStringIO import StringIO 
    def parse_all_fields(day_col, month_col, year_col, hour_col, minute_col,second_col): 
    day_col = _maybe_cast(day_col) 
    month_col = _maybe_cast(month_col) 
    year_col = _maybe_cast(year_col) 
    hour_col = _maybe_cast(hour_col) 
    minute_col = _maybe_cast(minute_col) 
    second_col = _maybe_cast(second_col) 
    return lib.try_parse_datetime_components(day_col, month_col, year_col, hour_col, minute_col, second_col) 
    ##Read the .txt file 
    data1 = pd.read_table('0132_3.TXT', sep='\s+', names=['Day','Month','Year','Hour','Min','Sec','Value']) 
    data1[:10] 

    Out[21]: 

    Day,Month,Year,Hour, Min, Sec, Value 
    29 04 13 18 15 00 7.667 
    29 04 13 18 30 00 7.000 
    29 04 13 18 45 00 7.000 
    29 04 13 19 00 00 7.333 
    29 04 13 19 15 00 7.000 

    data2 = pd.read_table(StringIO(data1), parse_dates={'datetime':['Day','Month','Year','Hour''Min','Sec']}, date_parser=parse_all_fields, dayfirst=True) 

TypeError         Traceback (most recent call last) 
    <ipython-input-22-8ee408dc19c3> in <module>() 
    ----> 1 data2 = pd.read_table(StringIO(data1), parse_dates={'datetime': ['Day','Month','Year','Hour''Min','Sec']}, date_parser=parse_all_fields, dayfirst=True) 

    TypeError: expected read buffer, DataFrame found 

在這一點上我堅持。首先,預期的讀取緩衝區錯誤令我困惑。我是否需要對.txt文件進行更多的預處理才能將日期轉換爲可讀格式?注意 - read_table的parse_function在這個日期格式上不能自行工作。

我是初學者 - 試圖學習。對不起,如果代碼是錯誤的/基本/混亂。如果有人能提供幫助,會非常感激。提前謝謝了。

回答

5

我認爲這將是更容易只是讀取CSV時解析日期他們:

In [1]: df = pd.read_csv('0132_3.TXT', header=None, sep='\s+\s', parse_dates=[[0]]) 

In [2]: df 
Out[2]: 
        0  1 
0 2013-04-29 00:00:00 7.667 
1 2013-04-29 00:00:00 7.000 
2 2013-04-29 00:00:00 7.000 
3 2013-04-29 00:00:00 7.333 
4 2013-04-29 00:00:00 7.000 

由於您使用需要指定一個日期解析器過一個不尋常的日期格式:

In [11]: def date_parser(ss): 
      day, month, year, hour, min, sec = ss.split() 
      return pd.Timestamp('20%s-%s-%s %s:%s:%s' % (year, month, day, hour, min, sec)) 

In [12]: df = pd.read_csv('0132_3.TXT', header=None, sep='\s+\s', parse_dates=[[0]], date_parser=date_parser) 

In [13]: df 
Out[13]: 
        0  1 
0 2013-04-29 18:15:00 7.667 
1 2013-04-29 18:30:00 7.000 
2 2013-04-29 18:45:00 7.000 
3 2013-04-29 19:00:00 7.333 
4 2013-04-29 19:15:00 7.000 
+0

Andy,非常感謝你 - 我看你做了什麼 - 它完美的工作。 –

相關問題