Skip to main content
 首页 » 编程设计

python之用 Pandas 加载不同列号的csv

2025年04月02日14exmyth

我有一个 csv 文件,其中总是有两个第一列,但不同文件的列数不同。 csv 可以如下所示:

Gondi,4012,227,233,157,158,149,158 
Gondi,4013,227,231,156,159,145,153 
Gondu,4014,228,233,157,158,145,153 
Gondu,4015,227,231,156,159,149,158 

目前我正在使用 NumPy,加载此数据的代码是:

import numpy as np 
def readfile(fname): 
    with open(fname) as f: 
       ncols = len(f.readline().split(',')) 
    name = np.loadtxt(fname, delimiter=',', usecols=[0],dtype=str) 
    ind  = np.loadtxt(fname, delimiter=',', usecols=[1],dtype=int) 
    data = np.loadtxt(fname, delimiter=',', usecols=range(2,ncols),dtype=int) 
    return data,name,ind 

我可以用 pandas 更有效地做同样的事情吗?

请您参考如下方法:

我想你可以使用 read_csv和 iloc对于选择第一、第二和其他列:

import pandas as pd 
import io 
 
temp=u"""Gondi,4012,227,233,157,158,149,158 
Gondi,4013,227,231,156,159,145,153 
Gondu,4014,228,233,157,158,145,153 
Gondu,4015,227,231,156,159,149,158""" 
#after testing replace io.StringIO(temp) to filename 
df = pd.read_csv(io.StringIO(temp), header=None) 
print df 
 
name = df.iloc[:,0] 
print name 
0    Gondi 
1    Gondi 
2    Gondu 
3    Gondu 
Name: 0, dtype: object 
 
ind = df.iloc[:,1] 
print ind 
0    4012 
1    4013 
2    4014 
3    4015 
Name: 1, dtype: int64 
 
data = df.iloc[:,2:] 
print data 
     2    3    4    5    6    7 
0  227  233  157  158  149  158 
1  227  231  156  159  145  153 
2  228  233  157  158  145  153 
3  227  231  156  159  149  158