Skip to main content
 首页 » 编程设计

python之使用 Python 从文件中删除最后一列

2025年05月04日35虾米姐

我基本上是想和这个人做同样的事情,但使用 Python: How can i delete last column from my text file

如何删除我的最后一列?

我尝试先使用 numpy.loadtxt 加载文本,然后忽略最后一个数组,但它根本不会加载,因为最后一列包含字符串,而不是 float 。

请您参考如下方法:

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.]