Home >Backend Development >Python Tutorial >How to Extract Pandas Series and Index as NumPy Arrays and Python Lists?
Accessing Pandas Series and Index as NumPy Arrays and Python Lists
In Python's Pandas library, it's often necessary to extract data from DataFrames as NumPy arrays or Python lists for further processing. This article addresses how to accomplish this task with both index and columns.
Getting a NumPy Array
To obtain a NumPy array of the index or column data, utilize the values attribute. For instance, to get the index values as a NumPy array:
<code class="python">df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']) print(df.index.values) # ['a', 'b', 'c'] print(df['A'].values) # [1, 2, 3]</code>
The values attribute provides direct access to the underlying data storage, eliminating the need for conversion.
Getting a Python List
To get the index or column data as a Python list, call the tolist() method:
<code class="python">print(df.index.tolist()) # ['a', 'b', 'c'] print(df['A'].tolist()) # [1, 2, 3]</code>
Note that this method can also be used for accessing data from other Pandas objects, such as Series.
The above is the detailed content of How to Extract Pandas Series and Index as NumPy Arrays and Python Lists?. For more information, please follow other related articles on the PHP Chinese website!