current position:Home>Pandas: how to create an empty data frame with column names

Pandas: how to create an empty data frame with column names

2022-01-30 11:56:32 Stone sword


You can use the following basic syntax to create an empty column with a specific column name pandas DataFrame.

df = pd.DataFrame(columns=['Col1', 'Col2', 'Col3'])

 Copy code 

The following example shows how to use this syntax in practice .

example 1: Create a with column names and no rows DataFrame

The following code shows how to create a with a specific column name and no rows pandas DataFrame.

import pandas as pd

#create DataFrame
df = pd.DataFrame(columns=['A', 'B', 'C', 'D', 'E'])

#view DataFrame
df

A   B   C   D   E


 Copy code 

We can use shape To get DataFrame Size .

#display shape of DataFrame
df.shape

(0, 5)
 Copy code 

This tells us DataFrame Yes 0 Row sum 5 Column .

We can also use **list()** To get a list of column names .

#display list of column names
list(df)

['A', 'B', 'C', 'D', 'E']

 Copy code 

example 2: Create a with column names and a specific number of rows DataFrame

The following code shows how to create a with a specific column name and a specific number of rows pandas DataFrame.

import pandas as pd

#create DataFrame
df = pd.DataFrame(columns=['A', 'B', 'C', 'D', 'E'],
                  index=range(1, 10))
#view DataFrame
df

        A	B	C	D	E
1	NaN	NaN	NaN	NaN	NaN
2	NaN	NaN	NaN	NaN	NaN
3	NaN	NaN	NaN	NaN	NaN
4	NaN	NaN	NaN	NaN	NaN
5	NaN	NaN	NaN	NaN	NaN
6	NaN	NaN	NaN	NaN	NaN
7	NaN	NaN	NaN	NaN	NaN
8	NaN	NaN	NaN	NaN	NaN
9	NaN	NaN	NaN	NaN	NaN
 Copy code 

Please note that ,DataFrame Each value in is filled with a NaN value .

Once again, , We can use shape To obtain a DataFrame Size .

#display shape of DataFrame
df.shape

(9, 5)
 Copy code 

This tells us ,DataFrame Yes 9 That's ok 5 Column .

Other resources

The following tutorial explains how to pandas Perform other common operations in .

How to be in Pandas Create a new column according to the condition in
How to be in Pandas Insert a column into the data frame
How to be in Pandas Set column as index in

The postPandas: How to Create Empty DataFrame with Column Namesappeared first onStatology.

copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301156299459.html

Random recommended