将带有标题和数据类型的pandas数据框转换为numpy数组

5

我一直在尝试将pandas DataFrame转换为numpy数组,保留数据类型和标题名称以便参考。由于使用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')])

我是否漏掉了什么,或者有其他方法可以做到这一点?我有很多要转换的数据框,它们的数据类型和列名不同,因此我需要自动化的方法。由于数据框数量庞大,我还需要它具有高效性。


请参考另一种方法(可以将pandas的dtype=object转换为numpy的dtype=string):https://stackoverflow.com/questions/52579601/convert-dataframe-with-strings-to-a-record-array/52749127#52749127 - JohnE
1个回答

9
使用 df.to_records() 将您的数据框转换为结构化数组。
您可以传递 index=False 以从结果中删除索引。
import numpy as np

df = pd.DataFrame(np.random.rand(10,3),columns=['Acol','Ccol','Bcol'])

res = df.to_records(index=False)

# rec.array([(0.12448699852020828, 0.7621451848466592, 0.0958529943831431),
#  (0.14534869167076214, 0.695297214355628, 0.3753874117495527),
#  (0.09890006207909052, 0.46364777245941025, 0.10216301104094272),
#  (0.3467673672203968, 0.4264108141950761, 0.1475998692158026),
#  (0.9272619907467186, 0.3116253419608288, 0.5681628329642517),
#  (0.34509767424461246, 0.5533523959180552, 0.02145207648054681),
#  (0.7982313824847291, 0.563383955627413, 0.35286630304880684),
#  (0.9574060540226251, 0.21296949881671157, 0.8882413119348652),
#  (0.0892793829627454, 0.6157843461905468, 0.8310360916075473),
#  (0.4691016244437851, 0.7007146447236033, 0.6672404967622088)], 
#           dtype=[('Acol', '<f8'), ('Ccol', '<f8'), ('Bcol', '<f8')])

结构化数组始终只有一个维度,这是无法更改的。

但您可以通过以下方式获取其形状:

res.view(np.float64).reshape(len(res), -1).shape  # (10, 3)

就性能而言,如果您正在操作数据,最好使用numpy.array通过df.to_numpy()并将列名记录在具有整数键的字典中。


1
谢谢,非常完美。在numpy完成了繁重的处理之后,我确实需要进行ravel操作,以便将其转换回pandas dataframe:res_pd = pd.DataFrame(res.ravel())。 - GivenX
@GivenX 你是用代码转换为numpy数组还是只使用了df.to_records()函数? - redwolf_cr7
我刚刚使用了 df.to_records()。 - GivenX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接