Python数据分析-pandas基础-2-DataFrame基础操作

这篇博客介绍了Python数据分析库pandas中DataFrame的基础操作,包括索引、排序和合并。详细讲解了loc和iloc方法的用法,sort_index与sort_values的区别,以及堆叠合并(concat函数)和主键合并(merge函数)的应用场景和参数设置。
摘要由CSDN通过智能技术生成

一、索引

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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值