我正在尝试调用一个包含字符串的文件,这样我可以计算出那种类型的字符串中有多少,但是当我收到错误时,字符串无法转换为浮点数 . 该文件非常大,但小部分看起来像{K5,M2 K5,M0,M0,M2} . 我想计算每个匹配条目的数量 .
file = 'IMF.txt' spec_type = np.loadtxt(file, skiprows = 1, usecols = 1)
np.loadtxt默认需要数字数据 . 您可以为长度为2的字符串指定 dtype='S2' :
dtype='S2'
from io import StringIO import numpy as np file = StringIO(""" 0 K5 1 M2 3 K5 5 M0 6 M0 7 M2""") # replace file with 'IMF.txt' spec_type = np.loadtxt(file, skiprows=1, usecols=1, dtype='S2')
返回:
print(spec_type) array([b'K5', b'M2', b'K5', b'M0', b'M0', b'M2'], dtype='|S2')
1 回答
np.loadtxt默认需要数字数据 . 您可以为长度为2的字符串指定
dtype='S2'
:返回: