Skip to main content
 首页 » 编程设计

python之如何从没有python中特定列的数组中读取

2025年05月04日14yyy_WW

我有一个 dtype = object 的 numpy 数组(实际上是各种数据类型的列表)。所以它制作了一个二维数组,因为我有一个列表数组(?)。我想将此数组的每一行和仅某些列复制到另一个数组。我将数据从 csv 文件存储在这个数组中。此 csv 文件包含多个字段(列)和大量行。这是我用来将数据存储到数组中的代码块。

data = np.zeros((401125,), dtype = object) 
for i, row in enumerate(csv_file_object): 
    data[i] = row 

数据基本可以描绘如下

column1  column2  column3  column4  column5 .... 
1         none     2       'gona'    5.3 
2         34       2       'gina'    5.5 
3         none     2       'gana'    5.1 
4         43       2       'gena'    5.0 
5         none     2       'guna'    5.7 
.....     ....   .....      .....    .... 
.....     ....   .....      .....    .... 
.....     ....   .....      .....    .... 

我想删除中间不需要的字段。假设我不想要 column3。 如何从数组中只删除该列?或者只将相关列复制到另一个数组?

请您参考如下方法:

使用pandas .在我看来,对于像您这样的各种类型的数据,pandas.DataFrame 可能更合适。

from StringIO import StringIO 
from pandas import * 
import numpy as np 
 
data = """column1  column2  column3  column4  column5 
1         none     2       'gona'    5.3 
2         34       2       'gina'    5.5 
3         none     2       'gana'    5.1 
4         43       2       'gena'    5.0 
5         none     2       'guna'    5.7""" 
 
data = StringIO(data) 
print read_csv(data, delim_whitespace=True).drop('column3',axis =1) 

出局:

   column1 column2 column4  column5 
0        1    none  'gona'      5.3 
1        2      34  'gina'      5.5 
2        3    none  'gana'      5.1 
3        4      43  'gena'      5.0 
4        5    none  'guna'      5.7 

如果您需要一个数组而不是 DataFrame,请使用 to_records() 方法:

df.to_records(index = False) 
#output: 
rec.array([(1L, 'none', "'gona'", 5.3), 
           (2L, '34', "'gina'", 5.5), 
           (3L, 'none', "'gana'", 5.1), 
           (4L, '43', "'gena'", 5.0), 
           (5L, 'none', "'guna'", 5.7)],  
            dtype=[('column1', '<i8'), ('column2', '|O4'), 
                   ('column4', '|O4'), ('column5', '<f8')])