我基本上是試圖做同樣的事情,因爲這傢伙,但與Python: How can i delete last column from my text file最後一列與Python
如何刪除我的最後一列?
我試着先使用numpy.loadtxt
加載文本,然後忽略最後一個數組,但它根本不會加載,因爲最後一列包含字符串而不是浮點數。
我基本上是試圖做同樣的事情,因爲這傢伙,但與Python: How can i delete last column from my text file最後一列與Python
如何刪除我的最後一列?
我試着先使用numpy.loadtxt
加載文本,然後忽略最後一個數組,但它根本不會加載,因爲最後一列包含字符串而不是浮點數。
numpy.loadtxt
函數具有參數usecols
。從the documentation:
numpy.loadtxt(
fname,
dtype=<type 'float'>,
comments='#',
delimiter=None,
converters=None,
skiprows=0,
usecols=None,
unpack=False,
ndmin=0
)
Load data from a text file.
...
usecols : sequence, optional Which columns to read, with 0 being
the first. For example, usecols = (1,4,5) will extract the
2nd, 5th and 6th columns. The default, None, results in all
columns being read.
當然,這假定您事先知道文件中有多少列。
例如,給定以下文件test.txt
:
100 test1
200 test2
300 test3
加載與numpy.loadtxt("test.txt")
產生這個錯誤。
$ python -c "import numpy as np;np.loadtxt('test.txt')"
Traceback (most recent call last):
...
items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: could not convert string to float: test1
然而使用usecols
參數正常工作:
$ python -c "import numpy as np;print np.loadtxt('test.txt', usecols=(0,))"
[ 100. 200. 300.]
只是做到了這一點,我仍然得到錯誤:'TypeError:'int'對象不可迭代' – nikfilippas
我認爲你一定在做錯事。我添加了一個我曾用來測試的例子,我希望這能夠澄清。我想你可能不會傳遞一個元組或列表到usecols參數。試試'usecols = [0,1]'。 – mbarkhau
對,我明白你的意思。不過,我仍然收到上面描述的這個錯誤。我只需要第17列,所以我寫了'loadtxt =(「Filename」,skiprows = 1,delimiter =「,」,usecols =(17))''。那是錯的嗎? – nikfilippas
該代碼塊讀取文件爲其中usecols
用於指定的列需要一個「字符串數組」
numpy.loadtxt('input_file.txt', dtype=str, usecols=(1,2,3,4))
被讀入numpy數組。
輸出:
array([['MAX', 'Footprint', 'Center-X', 'Center-Y'],
['"100-0009"', '"1206', '-', 'CAPACITOR"'],
['"100-0009"', '"1206', '-', 'CAPACITOR"'],
['"100-0009"', '"1206', '-', 'CAPACITOR"'],
['"100-0009"', '"1206', '-', 'CAPACITOR"'],
['"100-0009"', '"1206', '-', 'CAPACITOR"'],
['"100-0009"', '"1206', '-', 'CAPACITOR"']],
dtype='|S10')
它不是。他的最後一欄包含花車,而不是弦。由於我最後一列包含字符串,因此出現錯誤。 – nikfilippas