Home  >  Article  >  Backend Development  >  How to Convert Pandas Series or Index to a NumPy Array or List?

How to Convert Pandas Series or Index to a NumPy Array or List?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 15:53:29120browse

How to Convert Pandas Series or Index to a NumPy Array or List?

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!

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