Home >Backend Development >Python Tutorial >How do you access DataFrame columns and rows as lists in Python\'s Pandas library?

How do you access DataFrame columns and rows as lists in Python\'s Pandas library?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 17:13:30695browse

How do you access DataFrame columns and rows as lists in Python's Pandas library?

Accessing DataFrame Columns and Rows as Lists

In Python's Pandas library, a DataFrame contains rows and columns of tabular data. To access the contents of a DataFrame column or row, you can use the following methods:

1. Getting Column Contents

To retrieve the contents of a DataFrame column as a list, use the tolist() method on the Series object representing the column. You can also cast the Series to a list using the list() function.

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

# Create a DataFrame from sample data
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']
})

# Convert column values to a list
cluster_list = df['cluster'].tolist()

# Alternatively, you can cast the Series to a list
cluster_list = list(df['cluster'])</code>

2. Getting Row Contents

To obtain the contents of a DataFrame row as a list, use the loc or iloc accessor with the appropriate row index.

<code class="python"># Get row 1 as a list using 'loc'
row_1_list = df.loc[0].tolist()

# Get row 1 as a list using 'iloc'
row_1_list = df.iloc[0].tolist()</code>

Sample Output:

cluster_list: ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
row_1_list: [1000, 4000, 'Y']

The above is the detailed content of How do you access DataFrame columns and rows as lists in Python\'s Pandas library?. 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