首页 > 解决方案 > Numpy 获取每列的 dtype

问题描述

我需要获取每列的类型以正确预处理它。

目前我通过以下方法做到这一点:

import pandas as pd

# input is of type List[List[any]]
# but has one type (int, float, str, bool) per column

df = pd.DataFrame(input, columns=key_labels)
column_types = dict(df.dtypes)
matrix = df.values

因为我只使用 pandas 来获取 dtypes(每列)并使用 numpy 来处理我想从我的项目中删除 pandas 的所有其他内容。

总之:有没有办法从 numpy 获取每列的(特定)dtypes

!或者:有没有一种快速的方法来重新计算ndarray的dtype(拼接矩阵后)

标签: pythonpandasnumpytypesdata-science

解决方案


如果你给出一个具体的例子会有所帮助,但我会用@jpp's列表来演示:

In [509]: L = [[0.5, True, 'hello'], [1.25, False, 'test']]
In [510]: df = pd.DataFrame(L)
In [511]: df
Out[511]: 
      0      1      2
0  0.50   True  hello
1  1.25  False   test
In [512]: df.dtypes
Out[512]: 
0    float64
1       bool
2     object
dtype: object

pandas不喜欢使用字符串 dtypes,所以最后一列是object.

In [513]: arr = df.values
In [514]: arr
Out[514]: 
array([[0.5, True, 'hello'],
       [1.25, False, 'test']], dtype=object)

因此,由于列 dtypes 中的混合,pandas正在制作整个事情object。我不太了解熊猫,不知道您是否可以更好地控制 dtype。

要从 中创建numpy结构化数组L,显而易见的事情是:

In [515]: np.array([tuple(row) for row in L], dtype='f,bool,U10')
Out[515]: 
array([(0.5 ,  True, 'hello'), (1.25, False, 'test')],
      dtype=[('f0', '<f4'), ('f1', '?'), ('f2', '<U10')])

这回答了如何为每个“列”指定不同的 dtype 的问题。但请记住,这个数组是 1d 的,并且fields没有columns.

但无论是否可以自动推断或设置 dtype,这都比较棘手。可能可以recarray从列中构建一个,或使用np.lib.recfunctions.

如果我使用列表“转置”,我可以将每一列格式化为一个单独的 numpy 数组。

In [537]: [np.array(col) for col in zip(*L)]
Out[537]: 
[array([0.5 , 1.25]),
 array([ True, False]),
 array(['hello', 'test'], dtype='<U5')]

然后将它们加入一个数组rec.fromarrays

In [538]: np.rec.fromarrays([np.array(col) for col in zip(*L)])
Out[538]: 
rec.array([(0.5 ,  True, 'hello'), (1.25, False, 'test')],
          dtype=[('f0', '<f8'), ('f1', '?'), ('f2', '<U5')])

或者我可以用来genfromtxtcsv格式中推断字段。

In [526]: np.savetxt('test.txt', np.array(L,object),delimiter=',',fmt='%s')
In [527]: cat test.txt
0.5,True,hello
1.25,False,test

In [529]: data = np.genfromtxt('test.txt',dtype=None,delimiter=',',encoding=None)
In [530]: data
Out[530]: 
array([(0.5 ,  True, 'hello'), (1.25, False, 'test')],
      dtype=[('f0', '<f8'), ('f1', '?'), ('f2', '<U5')])

推荐阅读