使用pandas加载不同列数的csv

时间:2016-04-21 06:17:48

标签: python csv numpy pandas

我有一个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做同样的事吗?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用read_csviloc来选择第一,第二和其他列:

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
相关问题