Home  >  Article  >  Backend Development  >  How to Retrieve NumPy Arrays and Python Lists from Pandas Indexes and Columns?

How to Retrieve NumPy Arrays and Python Lists from Pandas Indexes and Columns?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 15:48:29834browse

How to Retrieve NumPy Arrays and Python Lists from Pandas Indexes and Columns?

Retrieving NumPy Arrays from Pandas Indexes and Columns

When working with Pandas, accessing the index or specific columns as NumPy arrays or Python lists is a common requirement. Here's how you can achieve this:

Converting to NumPy Array

To obtain a NumPy array, leverage the values attribute. This attribute allows you to retrieve the underlying data without the need for explicit conversion:

<code class="python">import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c'])

# Get the index as a NumPy array
index_array = df.index.values
print(index_array) 
# Output: array(['a', 'b', 'c'], dtype=object)</code>

Converting to Python List

To retrieve the index or columns as Python lists, use the tolist() method:

<code class="python"># Get the index as a list
index_list = df.index.tolist()
print(index_list) # Output: ['a', 'b', 'c']</code>

Similarly, you can obtain the columns as lists by accessing the columns attribute and then applying the tolist() method.

The above is the detailed content of How to Retrieve NumPy Arrays and Python Lists from Pandas Indexes and Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn