gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:32:15 25 4
gpt4 key购买 nike

我有一个 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_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

关于python - 用 Pandas 加载不同列号的csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com