Home >Backend Development >Python Tutorial >How to Retrieve NumPy Arrays and Python Lists 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:
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>
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!