Python - Pandas - loc vs iloc (DataFrame.loc[:,['column_name':]])

原文链接:https://blog.csdn.net/weixin_48964486/article/details/123150832

————————————————————————————————————————————————

关于python数据分析常用库pandas中的DataFrame的loc和iloc取数据 基本方法总结归纳及示例如下:
1.准备一组DataFrame数据
import pandas as pd
df = pd.DataFrame({
'AAA': [120, 101, 106, 117, 114, 122],
'BBB': [115, 100, 110, 125, 123, 120],
'CCC': [109, 112, 125, 120, 116, 115],
'DDD': 'ABCDEFG'
}, index=[1, 2, 3, 4, 5, 6])
1
2
3
4
5
6
7
'
运行运行
2.loc 标签索引
loc通过标签 在DataFrame中选取数据

2.1 loc 获取行
2.1.1 loc 获取一行
print(df)
print("=======================")
# 获取一行数据
print(df.loc[1])
1
2
3
4


2.1.2 loc 获取多行
print(df)
print("=======================")
print(df.loc[[1, 3]])
1
2
3


2.1.3 loc 获取多行(切片)
print(df)
print("=======================")
print(df.loc[1:5])
1
2
3


2.2 loc获取指定数据(行&列)
当对行和列同时指定时,如果指定值不连续,则需要放在一个列表中;如果指定值是连续的,并采用切片的方式,则不需要加方括号。loc的参数中,左边表示行,右边表示列。

示例一
print(df)
print("=======================")
print(df.loc[2:4, ['AAA', 'CCC']])
1
2
3


示例二
print(df)
print("=======================")
print(df.loc[[1, 3], ['BBB', 'DDD']])
1
2
3


示例三
print(df)
print("=======================")
print(df.loc[:, 'BBB':])
1
2
3


3. iloc 位置索引
loc通过位置 在DataFrame中选取数据

3.1 iloc 获取行
3.1.1 iloc 获取单行
以获取第二行为例

print(df)
print("=======================")
print(df.iloc[1]) # 第2行
1
2
3


3.1.2 iloc 获取多行
获取下标为0,2的行(第1、3行)

print(df)
print("=======================")
print(df.iloc[[0, 2]]) # 第1、3行。
1
2
3


获取下标为1到3的行(第2、3、4行)

print(df)
print("=======================")
print(df.iloc[1: 4]) # 第2、3、4行。
1
2
3


获取下标为1的行,及其后边的所有行

print(df)
print("=======================")
print(df.iloc[1:]) # 第二行及以后。
1
2
3


3.2 iloc获取指定数据(行&列)
获取所有行,指定列
print("=======================")
print(df.iloc[:, [1, 3]])
1
2


获取所有行,指定连续的列
print("=======================")
print(df.iloc[:, :2])
1
2


获取指定行,指定列
print("=======================")
print(df.iloc[[2, 5], [1, 3]])
1
2

 

posted on 2024-07-21 11:43  frank_cui  阅读(12)  评论(0编辑  收藏  举报

导航

levels of contents