一、索引

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,['col1','col2']]
>
col1	col2
0	1	6
1	2	7
2	3	8
3	4	9

允许输入bool型数据和函数:

df.loc[df['col1']>3,:]#允许输入布尔型
>	
col1	col2
3	4	9
4	5	0

df.loc[lambda df:df['col1']>2,:]#允许输入含有一个参数的函数
>
	col1	col2
2	3	8
3	4	9
4	5	0

(2) iloc

iloc方法完全基于位置,它只接收整数,不接受索引名称。

#获取单列
df.iloc[:,0]
>
0    1
1    2
2    3
3    4
4    5
Name: col1, dtype: int64

#获取多列
df.iloc[:,0:2]
>
	col1	col2
0	1	6
1	2	7
2	3	8
3	4	9
4	5	0

#获取多行
df.iloc[0:3,1]
#注意,按照位置定位时,0:3就是0,1,2行。
>
0    6
1    7
2    8
Name: col2, dtype: int64

#获取多列多行
df.iloc[0:3,0:2]
>
col1	col2
0	1	6
1	2	7
2	3	8

#布尔型输入
df.iloc[df['col1'].values>2,:]
>	
col1	col2
2	3	8
3	4	9
4	5	0

3.MultiIndex方法

MultiIndex对象能在一个轴上拥有两个以上的索引。

multiindex=[['a','a','b','b','c','c'],['one','two','one','two','one','two']]
df1=pd.DataFrame(np.arange(12).reshape(6,2),columns=['col1','col2'],index=multiindex)
df1

col1col2
aone01
two23
bone45
two67
cone89
two1011

df1.index
>
MultiIndex([('a', 'one'),
            ('a', 'two'),
            ('b', 'one'),
            ('b', 'two'),
            ('c', 'one'),
            ('c', 'two')],
           )

访问

df1.loc[('a','two'),:]
>
col1    2
col2    3
Name: (a, two), dtype: int32

df1.loc[(['a','b'],['one','two']),'col1']
#访问第一索引层为a,b;第二索引层为one,two;列索引为col1的数据
>
a  one    0
   two    2
b  one    4
   two    6
Name: col1, dtype: int32

切片:使用pandas.IndexSlice方法

idx=pd.IndexSlice
df1.loc[idx['b','two'],:]
>
col1    6
col2    7
Name: (b, two), dtype: int32

df1.loc[idx[['b','c'],'one'],'col2']
>
b  one    5
c  one    9
Name: col2, dtype: int32

二、排序

1.sort_index方法

按索引排序

df.sort_index(axis,ascending,inplace)

axis=0表示按照行索引排序;1表示按照列索引排序。

ascending=True表示按照升序排列

inplace=True表示替换原数据

df.sort_index()
>

col1	col2
0	1	6
1	2	7
2	3	8
3	4	9
4	5	0

df.sort_index(axis=1,ascending=False)
>

col2	col1
0	6	1
1	7	2
2	8	3
3	9	4
4	0	5

2.sort_values方法

按值排序。

df.sort_values(by,axis=0,ascending=True,inplace=False)

df.sort_values(by='col2',ascending=False,axis=0)
>

col1	col2
3	4	9
2	3	8
1	2	7
0	1	6
4	5	0

df.sort_values(by=1,axis=1)
>
	col1	col2
0	1	6
1	2	7
2	3	8
3	4	9
4	5	0

3.nlargest和nsmallest

返回前n个最大值或最小值

df.nlargest(2,'col1')
>	
col1	col2
4	5	0
3	4	9

df.nsmallest(3,'col2')
>
	col1	col2
4	5	0
0	1	6
1	2	7

三、合并

1.堆叠合并

pandas.concat函数

(1)横向堆叠

设置axis=1,按照行索引的名称将两张表进行横向堆叠。

当两张表索引不完全一样时,可以使用join参数选择“inner”内连接(仅返回索引重叠部分)或者“outer”外连接(显示并集数据,没有值的地方用空值填补)。

df1=pd.DataFrame({'key':['A','B','C','D','E','F'],'values':[1,2,3,4,5,6]})
df2=pd.DataFrame({'key':['B','D','E','F'],'values':[7,8,9,0]})
pd.concat([df1,df2].axis=1)
>
	key	values	key	values
0	A	1	B	7.0
1	B	2	D	8.0
2	C	3	E	9.0
3	D	4	F	0.0
4	E	5	NaN	NaN
5	F	6	NaN	NaN

pd.concat([df1,df2],axis=1,join="inner")
>

key	values	key	values
0	A	1	B	7
1	B	2	D	8
2	C	3	E	9
3	D	4	F	0

(2)纵向堆叠

axis=0

pd.concat([df1,df2],axis=0)
>
	key	values
0	A	1
1	B	2
2	C	3
3	D	4
4	E	5
5	F	6
0	B	7
1	D	8
2	E	9
3	F	0

2.主键合并

通过一个或多个键将两个数据集合并起来,类似于SQL中的JOIN ON。

pandas.merge函数将指定列作为主键来连接两个数据集。

pd.merge(df1,df2,on='key',how='inner')

keyvalues_xvalues_y
0B27
1D48
2E59
3F60
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐