How do I extract data from a Pandas DataFrame as a list?

DDD
Release: 2024-10-27 12:58:30
Original
902 people have browsed it

How do I extract data from a Pandas DataFrame as a list?

Extracting Data from a Pandas DataFrame as a List

In a Pandas DataFrame, each column represents a Pandas Series, which can be converted into a Python list. This capability enables efficient iteration through the data and allows for further processing and visualization.

To extract the contents of a column as a list, the .tolist() method or the list(x) cast can be utilized. For example, if you have a DataFrame df with a column named 'cluster', you can retrieve its contents as a list using the following code:

column1_list = df['cluster'].tolist()
Copy after login

Alternatively, if you want to obtain the entire column or row as a list, you can employ the .to_numpy() method, which converts the data to a NumPy array, or the .values() property, which returns a 2D NumPy array representing the DataFrame's data.

For instance, to extract the entire first column as a list, you would use:

column1_list = df[df.columns[0]].tolist()
Copy after login

Or, to retrieve the first row as an array:

row1_array = df.iloc[0].to_numpy() # or df.iloc[0].values
Copy after login

By leveraging these techniques, you can easily extract data from Pandas DataFrames into lists for subsequent processing or analysis.

The above is the detailed content of How do I extract data from a Pandas DataFrame as a 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
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!