【发布时间】:2018-09-18 22:34:17
【问题描述】:
我一直在尝试将 pandas 数据帧转换为 numpy 数组,并保留 dtypes 和标头名称以便于参考。我需要这样做,因为对 pandas 的处理太慢了,numpy 快了 10 倍。我有来自 SO 的这段代码,除了结果看起来不像标准的 numpy 数组之外,它给了我我需要的东西 - 即它不显示形状中的列号。
[In]:
df = pd.DataFrame(randn(10,3),columns=['Acol','Ccol','Bcol'])
arr_ip = [tuple(i) for i in df.as_matrix()]
dtyp = np.dtype(list(zip(df.dtypes.index, df.dtypes)))
dfnp= np.array(arr_ip, dtype=dtyp)
print(dfnp.shape)
dfnp
[Out]:
(10,) #expecting (10,3)
array([(-1.0645345 , 0.34590193, 0.15063829),
( 1.5010928 , 0.63312454, 2.38309797),
(-0.10203999, -0.40589525, 0.63262773),
( 0.92725915, 1.07961763, 0.60425353),
( 0.18905164, -0.90602597, -0.27692396),
(-0.48671514, 0.14182815, -0.64240004),
( 0.05012859, -0.01969079, -0.74910076),
( 0.71681329, -0.38473052, -0.57692395),
( 0.60363249, -0.0169229 , -0.16330232),
( 0.04078263, 0.55943898, -0.05783683)],
dtype=[('Acol', '<f8'), ('Ccol', '<f8'), ('Bcol', '<f8')])
是我遗漏了什么还是有其他方法可以做到这一点?我有许多要转换的 df,它们的 dtypes 和列名各不相同,所以我需要这种自动化方法。由于大量的df,我还需要它高效。
【问题讨论】:
-
仅供参考,这里的另一种方法(优点是将 pandas dtype=object 转换为 numpy dtype=string:stackoverflow.com/questions/52579601/…
标签: python arrays pandas numpy dataframe