Converting Pandas Series or Index to NumPy Array
Obtaining a NumPy array or Python list from a Pandas index or column is a common need when working with data in Python. This can be achieved with ease using the Pandas library's attributes and methods.
NumPy Array
To convert an index or column to a NumPy array, utilize the values attribute. This attribute accesses the underlying data storage without the need for conversion:
<code class="python">import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']) index_array = df.index.values # Result: array(['a', 'b', 'c'], dtype=object) column_array = df['A'].values # Result: array([1, 2, 3])</code>
List
To convert the index to a list, use the tolist() method:
<code class="python">index_list = df.index.tolist() # Result: ['a', 'b', 'c']</code>
Similarly, this method can be applied to columns to obtain a list of values.
The above is the detailed content of How to Convert Pandas Series or Index to a NumPy Array or List?. For more information, please follow other related articles on the PHP Chinese website!