SoFunction
Updated on 2024-12-20

How python pandas reads rows or columns of data using loc and iloc

Create a DataFrame

data = {'name':['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu'],'age':[20, 21, 22, 23], 'gender': [0, 1, 1, 1], 'stature': [165, 189, 178, 160], 'year': [2000, 2002, 2003, 1993]}
df = (data)
print (df)

The results of the run are as follows:

  name  age  gender  stature  year
0 Zhang 20 0 165 2000
1 Li Si 21 1 189 2002
2 Wang Wu 22 1 178 2003
3 Zhao Liu 23 1 160 1993

I. Using the loc method to read data

loc: access by tagged values (column and row index values), support for single-value access or sliced queries, you can also specify the return column variable

1.1 Reading the value of a row or column

# 1. Read the second line, the name of the second line is "1".
df1= [1]
'''
name the fourth child in the family
age 21
gender 1
stature 189
year 2002
Name: 1, dtype: object
'''
# 2. Read the second column, which has the name age.
df2 = [ : ,"age"]
'''
0    20
1    21
2    22
3    23
Name: age, dtype: int64
'''
# 3. read a value at the same time, read the value with row number 2 and column name
df3 = [2, 'name']
# 'Wang Wu'

1.2 Reading a region

# Read the values in rows 1 through 2, age through stature columns.
df4 = [ 1:2, "age":"stature"]
df4

1.3 Screening by condition

Single-criteria filtering

# Single-criteria filtering: reading people older than 20 years old
df5 = [  > 20]

Multi-criteria filtering

# Multi-criteria filtering: read people older than 20 and with a stature of 180 or more.
df5 = [( > 20) & (> 180)]
df5

Conditions + Slices

# Read people older than 20, and only display name and feature
df5 = [  > 20, ['name', 'stature']]
df5

II. Reading data using the iloc method

iloc: accessed via row index and column index positions (numeric index), supports single-value access or sliced queries

2.1 Reading the value of a row or column

# 1. read the value of the second line, the first line starts at 0
df1= [1]
'''
name the fourth child in the family
age 21
gender 1
stature 189
year 2002
Name: 1, dtype: object
'''
# 2. Read the second column, the first one starts at 0
df2 = [ : , 1]
'''
0    20
1    21
2    22
3    23
Name: age, dtype: int64
'''
# 3. Reads a value at the same time, reads the value in row 3, column 1. The first column starts at 0
df3 = [2, 0]
# 'Wang Wu'

2.2 Reading data from a region

# Read rows 2 and 3, columns 3 and 4 #
df1 = [1:3, 2:4]
df1 

summarize

to this article on python pandas how to use loc and iloc read rows or columns of data on this article, more related pandas loc and iloc read rows and columns of data content, please search for my previous posts or continue to browse the following articles hope that you will support me in the future!