文章目錄
- 1.準備一組DataFrame資料
- 2.loc 標簽索引
- 2.1 loc 獲取行
- 2.1.1 loc 獲取一行
- 2.1.2 loc 獲取多行
- 2.1.3 loc 獲取多行(切片)
- 2.2 loc獲取指定資料(行&列)
- 3. iloc 位置索引
- 3.1 iloc 獲取行
- 3.1.1 iloc 獲取單行
- 3.1.2 iloc 獲取多行
- 3.2 iloc獲取指定資料(行&列)
關于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])
2.loc 標簽索引
loc通過標簽 在DataFrame中選取資料
2.1 loc 獲取行
2.1.1 loc 獲取一行
print(df)
print("=======================")
# 獲取一行資料
print(df.loc[1])

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

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

2.2 loc獲取指定資料(行&列)
當對行和列同時指定時,如果指定值不連續,則需要放在一個串列中;如果指定值是連續的,并采用切片的方式,則不需要加方括號,loc的引數中,左邊表示行,右邊表示列,
- 示例一
print(df)
print("=======================")
print(df.loc[2:4, ['AAA', 'CCC']])

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

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

3. iloc 位置索引
loc通過位置 在DataFrame中選取資料
3.1 iloc 獲取行
3.1.1 iloc 獲取單行
以獲取第二行為例
print(df)
print("=======================")
print(df.iloc[1]) # 第2行

3.1.2 iloc 獲取多行
獲取下標為0,2的行(第1、3行)
print(df)
print("=======================")
print(df.iloc[[0, 2]]) # 第1、3行,

獲取下標為1到3的行(第2、3、4行)
print(df)
print("=======================")
print(df.iloc[1: 4]) # 第2、3、4行,

獲取下標為1的行,及其后邊的所有行
print(df)
print("=======================")
print(df.iloc[1:]) # 第二行及以后,

3.2 iloc獲取指定資料(行&列)
- 獲取所有行,指定列
print("=======================")
print(df.iloc[:, [1, 3]])

- 獲取所有行,指定連續的列
print("=======================")
print(df.iloc[:, :2])

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

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/433328.html
標籤:AI
