In our previous article, we discussed how to select rows from a DataFrame using loc[] and iloc[] in pandas. In this article, we will discuss how we can select both rows and columns from a DataFrame using loc[] and iloc[] in pandas.
In this article, we will discuss:
- How to select a specific row and a column from a DataFrame using pandas?
- How to select multiple rows and a single column from a DataFrame using pandas?
- How to select multiple rows and multiple columns from a DataFrame using pandas?
How to select a specific row and a column from a DataFrame using pandas?
Let’s say we want to select a specific row and a column from a DataFrame using pandas. We can use the following Python code:
import pandas
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df1 = pandas.DataFrame(list1, index=["Row 1", "Row 2", "Row 3"], columns=["Column 1", "Column 2", "Column 3"])
print(df1)
n1 = df1.loc["Row 1", "Column 1"]
n2 = df1.iloc[0, 0]
print("n1: \n", n1)
print("Type of n1: ", type(n1))
print("n2: \n", n2)
print("Type of n2: ", type(n2))
Here, we are first creating a pandas DataFrame df1 from a Python list list1. Please note that the rows and columns of the DataFrame are labeled. If we print the DataFrame, it looks like the following:








































0 Comments