Filter
Learn how can we use filtering in pandas
retail sales dataset
11/24/2023
CUST001
Male
34
Beauty
3
50
2/27/2023
CUST002
Female
26
Clothing
2
500
1/13/2023
CUST003
Male
50
Electronics
1
30
5/21/2023
CUST004
Male
37
Clothing
1
500
5/6/2023
CUST005
Male
30
Beauty
2
50
4/25/2023
CUST006
Female
45
Beauty
1
30
3/13/2023
CUST007
Male
46
Clothing
2
25
2/22/2023
CUST008
Male
30
Electronics
4
25
12/13/2023
CUST009
Male
63
Electronics
2
300
10/7/2023
CUST010
Female
52
Clothing
4
50
2/14/2023
CUST011
Male
23
Clothing
2
50
10/30/2023
CUST012
Male
35
Beauty
3
25
Filter to get the first row
To get the first row , all you need to do is to pass index number of the row in loc.
# Assuming the DataFrame is named df
first_row = df.loc[0]
print(first_row)
11/24/2023
CUST001
Male
34
Beauty
3
50
Filter to get specific rows
To get rows from index 3 to 7 using .loc
, you can specify the index range. Here's how you can do it:
# Assuming the DataFrame is named df
rows_3_to_7 = df.loc[3:7]
print(rows_3_to_7)
This will output the following subset of the DataFrame:
5/21/2023
CUST004
Male
37
Clothing
1
500
5/6/2023
CUST005
Male
30
Beauty
2
50
4/25/2023
CUST006
Female
45
Beauty
1
30
3/13/2023
CUST007
Male
46
Clothing
2
25
2/22/2023
CUST008
Male
30
Electronics
4
25
Filter to get specific row and specific columns
To get rows from index 3 to 7 and only the first 3 columns using .loc
, you can specify both the index range and the columns you want. Here's how you can do it:
# Assuming the DataFrame is named df
rows_3_to_7_columns_1_to_3 = df.loc[3:7, df.columns[:3]]
print(rows_3_to_7_columns_1_to_3)
This will output the following subset of the DataFrame:
5/21/2023
CUST004
Male
5/6/2023
CUST005
Male
4/25/2023
CUST006
Female
3/13/2023
CUST007
Male
2/22/2023
CUST008
Male
Last updated