參考:https://blog.csdn.net/ly_ysys629/article/details/55107237
# header=0,表示文件第0行為列索引 # index_col=0,表示文件第0列為行索引 userTable=pd.read_csv('./data/preprefe_%s.csv'%str(i),header=0,index_col=0)
常用參數的讀取csv文件
import pandas as pd obj=pd.read_csv('f:/ceshi.csv') print obj print type(obj) print obj.dtypes
Unnamed: 0 c1 c2 c3
0 a 0 5 10
1 b 1 6 11
2 c 2 7 12
3 d 3 8 13
4 e 4 9 14
<class 'pandas.core.frame.DataFrame'>
Unnamed: 0 object
c1 int64
c2 int64
c3 int64
dtype: object
ceshi.csv為有列索引沒有行索引的數據,read_csv會自動加上行索引,即使原數據集有行索引。
read_csv讀取的數據類型為Dataframe,obj.dtypes可以查看每列的數據類型
obj_2=pd.read_csv('f:/ceshi.csv',header=None,names=range(2,5)) print obj_2
2 3 4
0 c1 c2 c3
1 0 5 10
2 1 6 11
3 2 7 12
4 3 8 13
5 4 9 14
header=None時,即指明原始文件數據沒有列索引,這樣read_csv為自動加上列索引,除非你給定列索引的名字。
obj_2=pd.read_csv('f:/ceshi.csv',header=0,names=range(2,5)) print obj_2
2 3 4
0 0 5 10
1 1 6 11
2 2 7 12
3 3 8 13
4 4 9 14
header=0,表示文件第0行(即第一行,python,索引從0開始)為列索引,這樣加names會替換原來的列索引。
obj_2=pd.read_csv('f:/ceshi.csv',index_col=0) print obj_2
- 1
- 2
c1 c2 c3
a 0 5 10
b 1 6 11
c 2 7 12
d 3 8 13
e 4 9 14
obj_2=pd.read_csv('f:/ceshi.csv',index_col=[0,2]) print obj_2
c1 c3
c2
a 5 0 10
b 6 1 11
c 7 2 12
d 8 3 13
e 9 4 14
index_col為指定數據中那一列作為Dataframe的行索引,也可以可指定多列,形成層次索引,默認為None,即不指定行索引,這樣系統會自動加上行索引(0-)
obj_2=pd.read_csv('f:/ceshi.csv',index_col=0,usecols=[0,1,2,3]) print obj_2
c1 c2 c3
a 0 5 10
b 1 6 11
c 2 7 12
d 3 8 13
e 4 9 14
obj_2=pd.read_csv('f:/ceshi.csv',index_col=0,usecols=[1,2,3]) print obj_2
c2 c3
c1
0 5 10
1 6 11
2 7 12
3 8 13
4 9 14
usecols:可以指定原數據集中,所使用的列。在本例中,共有4列,當usecols=[0,1,2,3]時,即選中所有列,之后令第一列為行索引,當usecols=[1,2,3]時,即從第二列開始,之后令原始數據集的第二列為行索引。
obj_2=pd.read_csv('f:/ceshi.csv',index_col=0,nrows=3) print obj_2
c1 c2 c3
a 0 5 10
b 1 6 11
c 2 7 12
nrows:可以給出從原始數據集中的所讀取的行數,目前只能從第一行開始到nrows行。