gpt4 book ai didi

python - 使用 numpy.loadtxt() 将文本文件作为字符串加载

转载 作者:IT老高 更新时间:2023-10-28 20:43:21 29 4
gpt4 key购买 nike

我想将一个大文本文件(大约 1 GB,3*10^6 行和 10 - 100 列)加载为包含字符串的 2D np 数组。但是,似乎 numpy.loadtxt() 仅将 float 作为默认值。是否可以为整个数组指定另一种数据类型?我试过以下没有运气:

loadedData = np.loadtxt(address, dtype=np.str)

我收到以下错误消息:

/Library/Python/2.7/site-packages/numpy-1.8.0.dev_20224ea_20121123-py2.7-macosx-10.8-x86_64.egg/numpy/lib/npyio.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)
833 fh.close()
834
--> 835 X = np.array(X, dtype)
836 # Multicolumn data are returned with shape (1, N, M), i.e.
837 # (1, 1, M) for a single row - remove the singleton dimension there

ValueError: cannot set an array element with a sequence

有什么想法吗? (我事先不知道我的文件中的确切列数。)

最佳答案

使用 genfromtxt反而。这是一种比 loadtxt 更通用的方法:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

使用文件col.txt:

foo bar
cat dog
man wine

这给出了:

[['foo' 'bar']
['cat' 'dog']
['man' 'wine']]

如果您希望每行具有相同的列数,请读取第一行并设置属性 filling_values 以修复任何缺失的行。

关于python - 使用 numpy.loadtxt() 将文本文件作为字符串加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985233/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com