How can I get the index or column of a DataFrame as a NumPy array or Python list?
Answers
You can easily retrieve the index or a specific column of a pandas DataFrame
as a NumPy array or a Python list using built-in methods.
1. Getting the Index:
To get the index of a DataFrame:
-
As a NumPy array:
numpy_array_index = df.index.to_numpy()
-
As a Python list:
list_index = df.index.tolist()
2. Getting a Column:
To get a specific column from a DataFrame:
-
As a NumPy array:
numpy_array_column = df['column_name'].to_numpy()
-
As a Python list:
list_column = df['column_name'].tolist()
Example:
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# Get index as NumPy array and list
index_array = df.index.to_numpy() # array([0, 1, 2])
index_list = df.index.tolist() # [0, 1, 2]
# Get column 'A' as NumPy array and list
column_array = df['A'].to_numpy() # array([1, 2, 3])
column_list = df['A'].tolist() # [1, 2, 3]
Key Functions:
.to_numpy()
: Converts the index or column into a NumPy array..tolist()
: Converts the index or column into a Python list.