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

Linda Hamilton
Release: 2024-10-20 15:53:29
Original
216 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template