python - 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(拼接矩阵后)
解决方案
如果你给出一个具体的例子会有所帮助,但我会用@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')])
或者我可以用来genfromtxt
从csv
格式中推断字段。
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')])
推荐阅读
- wpf - 弹出窗口未在触摸时关闭
- c# - 如何通过 GSM 调制解调器发送包含波斯文本的 SMS?
- python - 如何在 Python 中使用循环从 txt 文件中提取单词(行中的第二个和第三个)
- jasper-reports - 如何使用动态参数在 jaspersoft 中查询域
- mongodb - 在 mongodb 3.4 中查询
- javascript - 如何使 google recaptcha 响应宽度为 100%
- windows - 尝试使用 Visual Studio Code 进行调试时,Rust 应用程序崩溃
- android - 如何在没有 NDK 的情况下访问 android COM 端口
- workbox - 从 v2 升级到 v3 时的“templatedUrls”
- sublimetext3 - 具有不同扩展名的 XML 的 Sublime 构建