一、索引
1.基础索引方式
import pandas as pd
df=pd.DataFrame({'col1':[1,2,3,4,5],'col2':[6,7,8,9,0]})
df
>
col1 col2
0 1 6
1 2 7
2 3 8
3 4 9
4 5 0
#访问单列数据
df['col1']
>
0 1
1 2
2 3
3 4
4 5
Name: col1, dtype: int64
df.col1
>
0 1
1 2
2 3
3 4
4 5
Name: col1, dtype: int64
#访问单列多行数据
df['col1'][0:3]
>
0 1
1 2
2 3
Name: col1, dtype: int64
#访问多列多行数据,将列标签组成一个list
df[['col1','col2']][0:3]
>
col1 col2
0 1 6
1 2 7
2 3 8
#访问多行数据
df[:][0:3]
>
col1 col2
0 1 6
1 2 7
2 3 8
2.loc方法与iloc方法
(1)loc
loc是基于名称的索引方式,接收索引名称。它也可以接收整数,但是这个整数必须是已经存在的索引名称。
行索引在前,列索引在后。
#访问单列数据
df.loc[:,'col1']
>
0 1
1 2
2 3
3 4
4 5
Name: col1, dtype: int64
#访问多列数据
df.loc[:,['col1','col2']]
>
col1 col2
0 1 6
1 2 7
2 3 8
3 4 9
4 5 0
#访问单行数据
df.loc[0,:]
>
col1 1
col2 6
Name: 0, dtype: int64
#访问多行数据
df.loc[0:3,'col1']
#注意,这里的0:3是指行索引的名称,所以会返回0,1,2,3行的数据,而不是像0,1,2行的数据。
>
0 1
1 2
2 3
3 4
Name: col1, dtype: int64
#访问多行多列数据
df.loc[0:3,['c