[Python] How to create a table from list (basic operation of table creation / change of matrix name)

[Python] How to create a table from list (basic operation of table creation / change of matrix name)

About the basic operation of creating a table in python. A summary of how to create and operate a table based on one list data for easy understanding.

Use pandas DataFrame to create the table.

Official Page


**table of contents**
  1. [One-column table](# 1 One-column table)
  2. [Create Table](# 1-1 Create Table)
  3. [Rename column](# 1-2 Rename column)
  4. [Rename line](# 1-3 Rename line)
  5. [Change matrix name at the same time](# 1-4 Matrix name changed at the same time)
  6. [Multi-column table](# 2 Multi-column table)
  7. [Join in list state](Join in #list state)
  8. [Make a table and then join](# Make a table and then join)
  9. Join 4 Tables (# Join 4 Tables)

## 1. 1. One column table Create a table from the following one-dimensional list.

listA = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE']


### (1-1) Creating a table

pd.DataFrame (array) └ "pd": pandas Abbreviation. pd import └ "DataFrame": 2D table data

Creating a table


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1 = pd.DataFrame(listA)
df1

#output
	0
0	AAA
1	BBB
2	CCC
3	DDD

-The array is output as a table ・ The first column is the heading (index number from 0) ・ The first row is the column name (index number from 0)


▼ You can enter data directly in the argument

Creating a table (directly)


import pandas as pd
pd.DataFrame(['AAA', 'BBB', 'CCC', 'DDD'])

#output
	0
0	AAA
1	BBB
2	CCC
3	DDD

### (1-2) Change column name ① Designated when creating the table ② Change later ②-1. columns method ②-2. rename method

① Designated when creating the table

Specify columns = ['AAA'] in the DataFrame option. └ "AAA": Column name (optional)

Rename column


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df2 = pd.DataFrame(listA, columns=['Ah ah'])
df2

#output
Ah ah
0	AAA
1	BBB
2	CCC
3	DDD

#### ② Change later ##### ②-1. columns method

df.columns = ['AAA'] └ "df": Table data └ ".columns": Get column names └ "AAA": Column name to be assigned

Assign using the columns method.

Rename column (later)


df1.columns = ['Ah ah']
df1

#output
Ah ah
0	AAA
1	BBB
2	CCC
3	DDD

##### ②-2. rename method `df.rename(columns={n:'AAA'}) └ "df": Table data └ ".rename": Rename row / column └ "columns = {}": Change column name └ "n": Column name of the change source └ "AAA": Column name after change

rename can specify which column name to change and how. {Original column name: Modified column name}

Change with rename method


df1.rename(columns={0:'Ah ah'})

#output
Ah ah
0	AAA
1	BBB
2	CCC
3	DDD

### (1-3) Change the line name

① Designated when creating the table ② Change later ②-1. index method ②-2. rename method

① Designated when creating the table

Specify ʻindex = ['AAA','BBB' ,,,,]` in the DataFrame option. └ "AAA" "BBB": Line name (optional) └ Either character string or numerical value can be specified

** ▼ Specify by character string **

Rename column (character string)


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1 = pd.DataFrame(listA, index=['111','222','333','444'])
df1

#output
	0
111	AAA
222	BBB
333	CCC
444	DDD

** ▼ Specify numerically **

Column name change (numerical value)


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1 = pd.DataFrame(listA, index=[111,22.2,3.33,444])
df1

#output
	0
111.00	AAA
22.20	BBB
3.33	CCC
444.00	DDD

** ▼ Specify with a variable **

Column name change (numerical value)


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
indexA = ['111','222','333','444']

df1 = pd.DataFrame(listA, index=indexA)
df1

#output
	0
111	AAA
222	BBB
333	CCC
444	DDD

#### ② Change later ##### ②-1. index method

Specify df.index = ['AAA','BBB' ,,,,]. └ "AAA" "BBB": Line name (optional) └ Both character string and numerical value can be specified

Change index name later


df1.index = ['111','222','333','444']
df1

#output
	0
111	AAA
222	BBB
333	CCC
444	DDD

#### ② Change later ##### ②-2. rename method `df.rename(index={n:'AAA'}) └ "df": Table data └ ".rename": Rename row / column └ "index = {}": Change line name └ "n": Line name of the change source └ "AAA": Line name after change

rename can specify which column name to change and how. rename = (index = {original line name: changed line name})

Change with rename method


df1.rename(index={1:'111',3:'333'})

#output
	0
0	AAA
111	BBB
2	CCC
333	DDD

### (1-4) Change the matrix name at the same time

① Designated when creating the table ② Change later ②-1. index method ②-2. rename method

① Designated when creating the table

With DataFrame options columns=['AAA','BBB',,,,] index=['aaa','bbb',,,,] Is specified. └ "AAA" "BBB": Column name (optional) └ "aaa" "bbb": Line name (optional)

Specify a matrix


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1 = pd.DataFrame(listA, columns=['Ah ah'], index=['111','222','333','444'])
df1


#output
Ah ah
111	AAA
222	BBB
333	CCC
444	DDD

Specify a matrix (variable)


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
cols = ['Ah ah']
inds = ['111','222','333','444']

df1 = pd.DataFrame(listA, columns=cols, index=inds)
df1


#output
Ah ah
111	AAA
222	BBB
333	CCC
444	DDD

#### ② Change later ##### ②-2. rename method `df.rename(index={n:'AAA'}, columns={m:'BBB'}) └ "df": Table data └ ".rename": Rename row / column └ "index = {}": Change line name └ "n": Line name of the change source └ "AAA": Line name after change └ "columns = {}": Change column name └ "m": Column name of the change source └ "BBB": Column name after change

rename can specify which column name to change and how. rename (index = {original row name: modified row name}, columns = {original column name: modified column name})

Specify matrix (rename method)


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1 = pd.DataFrame(listA)

df1.rename(columns={0:'Good'}, index={1:'111', 3:'333', 4:'444'})


#output
Good
0	AAA
111	BBB
2	CCC
333	DDD

## 2. Multi-column table

Create a multi-column table from multiple lists.

Combine two lists.

list


listA = ['AAA', 'BBB', 'CCC', 'DDD']
listB = ['EEE', 'FFF', 'GGG', 'HHH']

Method ① Combine in the state of list ② Make a table and then join

① Combine in the state of list

  1. Make list A a table.
  2. Specify the column name and element to add.

df['aaa'] = ['AAA', 'BBB',,,] └ "df": Original table └ "aaa": Column name to be added (numerical value is also acceptable) └ "AAA" "BBB": Column elements

Add column


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1= pd.DataFrame(listA)

df1[1] =  ['EEE', 'FFF', 'GGG', 'HHH']
df1

#output
	0	1
0	AAA	EEE
1	BBB	FFF
2	CCC	GGG
3	DDD	HHH

Error if the number of elements is different


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
df1= pd.DataFrame(listA)

df1[1] =  ['EEE', 'FFF', 'GGG']
df1

#output
# ValueError: Length of values does not match length of index

### ② Make a table and then join Basically the same as the procedure for joining in the state of an array.
  1. Make list A a table.
  2. Turn listB into a table.
  3. Specify the column name in the table of listA and the table of listB in the element. df['aaa'] = dfB └ "df": Original table └ "aaa": Column name to be added (numerical value is also acceptable) └ "AAA" "BBB": Column elements

Add column


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
dfA= pd.DataFrame(listA)

listB =['EEE', 'FFF', 'GGG', 'HHH']
dfB= pd.DataFrame(listB)

dfA['1'] = dfB
dfA

#output
	0	1
0	AAA	EEE
1	BBB	FFF
2	CCC	GGG
3	DDD	HHH

※Caution Adding the tables with the operator "+" will add elements to the same column. (* Not a combination)

In the case of "+"


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
dfA= pd.DataFrame(listA)

listB =['EEE', 'FFF', 'GGG', 'HHH']
dfB= pd.DataFrame(listB)

dfA + dfB

#output
	0
0	AAAEEE
1	BBBFFF
2	CCCGGG
3	DDDHHH

### Join 4 tables Join the four tables from listA to D.

Original table


listA = ['AAA', 'BBB', 'CCC', 'DDD']
listB = ['EEE', 'FFF', 'GGG', 'HHH']
listC = ['III', 'JJJ', 'KKK', 'LLL']
listD = ['MMM', 'NNN', 'OOO', 'PPP']

** ▼ df ['column name'] = Created with list data ** └ "df": Original table

Join table


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
listB = ['EEE', 'FFF', 'GGG', 'HHH']
listC = ['III', 'JJJ', 'KKK', 'LLL']
listD = ['MMM', 'NNN', 'OOO', 'PPP']

dfA = pd.DataFrame(listA)
dfA[1] = listB
dfA[2] = listC
dfA[3] = listD

dfA


#output
	0	1	2	3
0	AAA	EEE	III	MMM
1	BBB	FFF	JJJ	NNN
2	CCC	GGG	KKK	OOO
3	DDD	HHH	LLL	PPP

▶ How to get rows / columns / values [here](https://qiita.com/yuta-38/items/69d03647e19eb29b0730)
[Return to top](How to create a table from #pythonlist Basic operation of table creation Matrix name change)

Recommended Posts

[Python] How to create a table from list (basic operation of table creation / change of matrix name)
[Python] How to get & change rows / columns / values from a table.
How to write a list / dictionary type of Python3
How to create a kubernetes pod from python code
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
How to get a list of built-in exceptions in python
Python: Create a dictionary from a list of keys and values
How to get a list of links from a page from wikipedia
How to create a Dockerfile (basic)
I tried to create a list of prime numbers with python
How to remove duplicates from a Python list while preserving order.
[Python] How to make a matrix of repeating patterns (repmat / tile)
How to create a clone from Github
[Python] How to convert a 2D list to a 1D list
How to create a repository from media
Summary of how to use Python list
[Python] How to put any number of standard inputs in a list
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to format a list of dictionaries (or instances) well in Python
[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
[Python] List Comprehension Various ways to create a list
Edit Excel from Python to create a PivotTable
How to open a web browser from python
How to clear tuples in a list (Python)
How to create a function object from a string
[python] Create a list of various character types
How to create a JSON file in Python
Basic operation list of Python3 list, tuple, dictionary, set
[python] Create table from pandas DataFrame to postgres
How to generate a Python object from JSON
How to pass the execution result of a shell command in a list in Python
How to get a list of files in the same directory with python
[Python] How to remove duplicate values from the list
[BigQuery] How to use BigQuery API for Python -Table creation-
[Python] How to create Correlation Matrix and Heat Map
How to save a table scraped by python to csv
Python script to create a JSON file from a CSV file
[Python] How to create a 2D histogram with Matplotlib
[Python] How to call a c function from python (ctypes)
Try to create a battle record table with matplotlib from the data of "Schedule-kun"
How to identify the element with the smallest number of characters in a Python list?
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to check in Python if one of the elements of a list is in another list
How to create a radial profile from astronomical images (Chandra, XMM etc.) using python
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
I wrote Python code to create a table (view) dependency diagram (PlantUML) from SQL
[python] Change the image file name to a serial number
How to slice a block multiple array from a multiple array in Python
How to run a Python program from within a shell script
How to launch AWS Batch from a python client app
I want to start a lot of processes from python
How to develop in a virtual environment of Python [Memo]
Procedure from environment construction to operation test of testinfra, a server environment test tool made by Python
How to display a list of installable versions with pyenv
How to get the last (last) value in a list in Python
How to change Python version
[Python] How to output a pandas table to an excel file
How to pass the execution result of a shell command in a list in Python (non-blocking version)
Overview of Python virtual environment and how to create it
How to connect the contents of a list into a string