我最近才切换到Python所以这个问题可能有一个非常简单的解决方案,但我似乎无法找到它。我有一个文本文件,格式如下:
data = np.loadtxt(fl_name,delimiter='\t',usecols=2)
我想要做的只是根据时间和日期绘制数据(例如第3列)。所以我使用
将第三列提取为Numpy数组date = np.genfromtxt(fl_name,delimiter='\t',usecols=0,converters={0: lambda x: datetime.strptime(x.decode('ascii'),"%d-%m-%y")})
time = np.genfromtxt(fl_name,delimiter='\t',usecols=1,converters={1: lambda x: datetime.strptime(x.decode('ascii'),"%H:%M:%S")})
我还想将日期和时间提取为一个数组,所以我尝试的是(希望我以后能以某种方式合并日期和时间):
In [166]: date
Out[166]:
array([datetime.datetime(1990, 5, 8, 0, 0),
datetime.datetime(1990, 5, 8, 0, 0),
datetime.datetime(1990, 5, 8, 0, 0), ...,
datetime.datetime(1992, 4, 7, 0, 0),
datetime.datetime(1992, 4, 7, 0, 0),
datetime.datetime(1992, 4, 7, 0, 0)], dtype=object)
In [167]: time
Out[167]:
array([datetime.datetime(1900, 1, 1, 0, 0),
datetime.datetime(1900, 1, 1, 3, 0),
datetime.datetime(1900, 1, 1, 6, 0), ...,
datetime.datetime(1900, 1, 1, 0, 0),
datetime.datetime(1900, 1, 1, 3, 0),
datetime.datetime(1900, 1, 1, 6, 0)], dtype=object)
那给了我
array([datetime.datetime(1990, 5, 8, 0, 0),
datetime.datetime(1990, 5, 8, 3, 0),
datetime.datetime(1990, 5, 8, 6, 0),
...
显然这不是我想要的,所以我的问题是 - 如何从我的文本文件中获取带有时间和日期的日期时间数组:
eclipse.ini
感谢您的投入!
答案 0 :(得分:0)
希望除了numpy之外你还可以使用pandas。如果是这样,组合列的日期时间就像:
df['datetime'] = pd.to_datetime(df.date + ' ' + df.time)
import pandas as pd
data = StringIO('\n'.join([x.strip() for x in u"""
08-05-90 0:00:00 1.78 7.1 10
08-05-90 3:00:00 2.01 7.4 11.1
08-05-90 6:00:00 1.74 7 10.5
08-05-90 9:00:00 1.97 7 11.1
08-05-90 12:00:00 1.78 6.3 11.1
""".split('\n')[1:-1]]))
df = pd.read_fwf(data, names='date time x y z'.split())
df['datetime'] = pd.to_datetime(df.date + ' ' + df.time)
print(df)
print(df.dtypes)
date time x y z datetime
0 08-05-90 0:00:00 1.78 7.1 10.0 1990-08-05 00:00:00
1 08-05-90 3:00:00 2.01 7.4 11.1 1990-08-05 03:00:00
2 08-05-90 6:00:00 1.74 7.0 10.5 1990-08-05 06:00:00
3 08-05-90 9:00:00 1.97 7.0 11.1 1990-08-05 09:00:00
4 08-05-90 12:00:00 1.78 6.3 11.1 1990-08-05 12:00:00
date object
time object
x float64
y float64
z float64
datetime datetime64[ns]