Home  >  Article  >  Backend Development  >  How can I extract data from a Pandas DataFrame as a Python list?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 16:00:04627browse

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>

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>

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>

Accessing Column as List:

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

Accessing Row as List:

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

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!

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