How can I extract data from a Pandas DataFrame as a Python list?

Barbara Streisand
Release: 2024-10-26 16:00:04
Original
626 people have browsed it

How can I extract data from a Pandas DataFrame as a Python list?

Accessing Data from Pandas DataFrames

To retrieve data from a Pandas DataFrame as a list, there are multiple methods available, depending on whether you want to access a specific column or row.

Accessing a Column as a List

To obtain the contents of a column as a list, you can use the following syntax:

<code class="python">column_list = df['column_name'].tolist()</code>
Copy after login

This will return a Python list containing the elements of the specified column.

Accessing a Row as a List

To retrieve a row as a list, you can use the iloc or loc methods, followed by .tolist():

<code class="python">row_list = df.iloc[row_index].tolist()  # row index-based
row_list = df.loc[row_label].tolist()  # row label-based</code>
Copy after login

Example

Consider the DataFrame:

<code class="python">import pandas as pd

df = pd.DataFrame({'cluster': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'load_date': ['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014', '4/1/2014', '7/1/2014', '8/1/2014', '9/1/2014'],
                   'budget': [1000, 12000, 36000, 15000, 12000, 90000, 22000, 30000, 53000],
                   'actual': [4000, 10000, 2000, 10000, 11500, 11000, 18000, 28960, 51200],
                   'fixed_price': ['Y', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N', 'N']})</code>
Copy after login

Accessing Column as List:

<code class="python">cluster_list = df['cluster'].tolist()  # ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']</code>
Copy after login

Accessing Row as List:

<code class="python">row_list = df.iloc[0].tolist()  # ['A', '1/1/2014', 1000, 4000, 'Y']</code>
Copy after login

The above is the detailed content of How can I extract data from a Pandas DataFrame as a Python list?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!