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在这个日期格式上不能自行工作。
我是初学者 - 试图学习。对不起,如果代码是错误的/基本/混乱。如果有人能提供帮助,会非常感激。提前谢谢了。
Andy,非常感谢你 - 我看你做了什么 - 它完美的工作。 –