可能最简单 - 与 Pandas 一起工作DataFrame
而不是数组
说实话,虽然 Numpy 数组可以与异构列一起使用,但在这种情况下,它们可能不是大多数用户实际需要的。对于许多用例,您最好使用Pandas DataFrame https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html。以下是将两列转换为一列的方法DataFrame
called df
:
import numpy as np
import pandas as pd
a = np.array([['2018-04-01T15:30:00'],
['2018-04-01T15:31:00'],
['2018-04-01T15:32:00'],
['2018-04-01T15:33:00'],
['2018-04-01T15:34:00']], dtype='datetime64[s]')
c = np.array([0,1,2,3,4]).reshape(-1,1)
df = pd.DataFrame(dict(date=a.ravel(), val=c.ravel()))
print(df)
# output:
# date val
# 0 2018-04-01 15:30:00 0
# 1 2018-04-01 15:31:00 1
# 2 2018-04-01 15:32:00 2
# 3 2018-04-01 15:33:00 3
# 4 2018-04-01 15:34:00 4
然后,您可以像这样处理每个列:
print(df['date'])
# output:
# 0 2018-04-01 15:30:00
# 1 2018-04-01 15:31:00
# 2 2018-04-01 15:32:00
# 3 2018-04-01 15:33:00
# 4 2018-04-01 15:34:00
# Name: date, dtype: datetime64[ns]
DataFrame
对象提供了大量方法,使分析此类数据变得非常容易。请参阅熊猫文档 https://pandas.pydata.org/pandas-docs/stable/dsintro.html(或本网站上的其他 QA)了解更多信息DataFrame
对象。
Numpy 唯一的解决方案 - 结构化数组
一般来说,你应该避免数组dtype=object
如果可以的话。它们会导致许多基本 Numpy 运算(例如算术,例如arr0 + arr1
),并且他们的行为方式可能出乎您的意料。
更好的纯 Numpy 解决方案是结构化数组。这些数组有一个复合dtype
,每个字段一个部分(为了便于讨论,“字段”相当于“列”,尽管您可以用字段做更多有趣的事情 https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html#structured-datatype-creation)。鉴于你的a
and c
数组,以下是创建结构化数组的方法:
# create the compound dtype
dtype = np.dtype(dict(names=['date', 'val'], formats=[arr.dtype for arr in (a, c)]))
# create an empty structured array
struct = np.empty(a.shape[0], dtype=dtype)
# populate the structured array with the data from your column arrays
struct['date'], struct['val'] = a.T, c.T
print(struct)
# output:
# array([('2018-04-01T15:30:00', 0), ('2018-04-01T15:31:00', 1),
# ('2018-04-01T15:32:00', 2), ('2018-04-01T15:33:00', 3),
# ('2018-04-01T15:34:00', 4)],
# dtype=[('date', '<M8[s]'), ('val', '<i8')])
然后,您可以通过使用名称索引来访问特定列(就像使用DataFrame
):
print(struct['date'])
# output:
# ['2018-04-01T15:30:00' '2018-04-01T15:31:00' '2018-04-01T15:32:00'
# '2018-04-01T15:33:00' '2018-04-01T15:34:00']
结构化数组的陷阱
例如,您不能添加两个结构化数组:
# doesn't work
struct0 + struct1
但您可以添加两个结构化数组的字段:
# works great
struct0['val'] + struct1['val']
一般来说,这些字段的行为就像标准 Numpy 数组一样。