[Python learning part 3] Convert pandas DataFrame, Series, and standard List to each other

At the beginning

--I want to convert DataFrame, Series, and standard list used in pandas to each other. --When using data processed by pandas in other libraries, it may only support list, so don't worry.

Work environment

Reference site

-Convert pandas.DataFrame, Series and Python standard list to each other -Pandas User Guide "Indexing and Selecting Data" (Official Document Japanese Translation)

Actually try

--Convert from list to dataframe, series --Convert from series to list --Convert from dataframe to list, series

Convert from list to dataframe, series

list→series

#Import pandas and rename it to pd
import pandas as pd
#View from Create List of Standard Library
l_1d = [0, 1, 2]
l_1d

#[0, 1, 2]
#Next, type convert list to series
s = pd.Series(l_1d)
s

#0    0
#1    1
#2    2
#dtype: int64
#If nothing is specified, index is automatically determined from 0
#Next, convert from list to series type while specifying index
s = pd.Series(l_1d, index=['row1', 'row2', 'row3'])
s

#row1    0
#row2    1
#row3    2
#dtype: int64
#You can also specify up to index at once
#It has nothing to do with this article, but it may be used for other purposes
s = pd.Series({"row1":0,"row2":1,"row3":2})
s

#row1    0
#row2    1
#row3    2
#dtype: int64

list→dataframe

#Prepare a two-dimensional array for conversion to a data frame
l_2d = [[0, 1, 2], [3, 4, 5]]

df = pd.DataFrame(l_2d)
df

#	1	2
#0	0	1	2
#1	3	4	5
#index,It is also possible to create a dataframe by specifying both columns
df = pd.DataFrame(l_2d,
                  index=['row1', 'row2'],
                  columns=['col1', 'col2', 'col3'])
df

#	col1	col2	col3
#row1	0	1	2
#row2	3	4	5
#Index at once,You can also specify up to column
#It has nothing to do with this article, but it may be used for other purposes
df = pd.DataFrame([[1,2,3],[4,5,6]],["row1","row2"],["col1","col2","col3"])
df

#	col1	col2	col3
#row1	1	2	3
#row2	4	5	6

Convert from series to list

series→list

#First, create a series
s = pd.Series([0, 1, 2])
print(s)

# 0    0
# 1    1
# 2    2
# dtype: int64
#Get only the value of series as list type
l_1d = s.values.tolist()
print(l_1d)

#[0, 1, 2]

Convert from dataframe to list, series

dataframe→list

#Create dataframe
df = pd.DataFrame([[0, 1, 2], [3, 4, 5]])
print(df)

#   0  1  2
#0  0  1  2
#1  3  4  5
#Get only the value of dataframe as list type
#index and columns are ignored
l_2d = df.values.tolist()
print(l_2d)

#[[0, 1, 2], [3, 4, 5]]
#If you get the dataframe as a list type, it becomes a two-dimensional array.
#How to convert 2D to 1D array
#It doesn't matter, but if there is, maybe I'll use it someday?

#I will use numpy so I will import it
import numpy as np
#Convert from standard library list type to array type
#Both are arrays
arr_list = np.array(l_2d)
arr_list.flatten().tolist()

#[0, 1, 2, 3, 4, 5]

dataframe→series

#Create a dataframe
df = pd.DataFrame([[0, 1, 2], [3, 4, 5]],["row1","row2"],["col1","col2","col3"])
print(df)

#      col1  col2  col3
#row1     0     1     2
#row2     3     4     5
#Get column as series
df_toSer = df["col1"]
df_toSer

#row1    0
#row2    3
#Name: col1, dtype: int64
#Get index as series
df_toSer2 = df.iloc[0]
df_toSer2

#col1    0
#col2    1
#col3    2
#Name: row1, dtype: int64

At the end

This is the site that I referred to this time. -Convert pandas.DataFrame, Series and Python standard list to each other -Pandas User Guide "Indexing and Selecting Data" (Official Document Japanese Translation)

Recommended Posts

[Python learning part 3] Convert pandas DataFrame, Series, and standard List to each other
[Python] Convert list to Pandas [Pandas]
[Python] Convert general-purpose container and class to each other
[Python] What is pandas Series and DataFrame?
Basic operation of Python Pandas Series and Dataframe (1)
Python application: Pandas Part 2: Series
Convert from Pandas DataFrame to System.Data.DataTable using Python for .NET
To go back and forth between standard python, numpy, pandas ①
[Python] How to use Pandas Series
Python> list> Convert double list to single list
[Python] How to add rows and columns to a table (pandas DataFrame)
[Python] How to convert a 2D list to a 1D list
Try converting latitude / longitude and world coordinates to each other with python
Python application: Pandas Part 4: DataFrame concatenation / combination
[Python] Add total rows to Pandas DataFrame
Read CSV file with Python and convert it to DataFrame as it is
Adding Series to columns in python pandas
Python learning notes for machine learning with Chainer Chapters 11 and 12 Introduction to Pandas Matplotlib
[python] Create table from pandas DataFrame to postgres
How to convert SVG to PDF and PNG [Python]
List of Python code to move and remember
Convert pandas dataframe elements to regular string type
Convert strings to character-by-character list format with python
pandas series part 1
Convert timezoned date and time to Unixtime in Python2.7
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
Mayungo's Python Learning Note: List of stories and links
Convert comma-separated numeric strings to numbers in Pandas DataFrame
How to convert JSON file to CSV file with Python Pandas
[Python] How to sort dict in list and instance in list
Introduction to Python numpy pandas matplotlib (~ towards B3 ~ part2)
[python] Use DataFrame to label arbitrary variables and arrays together and save them in csv [pandas]
Convert 202003 to 2020-03 with pandas
Python application: Pandas # 3: Dataframe
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
How to convert Youtube to mp3 and download it super-safely [Python]
Graph time series data in Python using pandas and matplotlib
Machine learning to learn with Nogizaka46 and Keyakizaka46 Part 1 Introduction
Convert video to black and white with ffmpeg + python + opencv
[Python] Random data extraction / combination from DataFrame using random and pandas
Go language to see and remember Part 8 Call GO language from Python
[python] Use DataFrame to label arbitrary variables and arrays together and save them in csv [pandas] Re-UP