Ben10
Ben10

Reputation: 297

How to create empty column with a specific number in dataframe python?

I am new to python and I want to know how to create empty column with a specific number. Let's say I want to create 20 columns. What I tried:

import pandas as pd
num =20 

for i in range(num):
    df = df + pd.DataFrame(columns=['col'+str(i)])

But I got the unwanted result:

Empty DataFrame
Columns: [col0, col1, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19, col2, col3, col4, col5, col6, col7, col8, col9]
Index: []

Desired result:

Empty DataFrame
Columns: [col0, col1, col2,...,col19]
Index: []

How to rectify it? Any help will be much appreciated!

Upvotes: 1

Views: 256

Answers (2)

RJ Adriaansen
RJ Adriaansen

Reputation: 9639

Assuming you wish to create an empty dataframe, the solution is to remove the for loop, and use a list comprehension for the column names:

import pandas as pd
num =20 
df = pd.DataFrame(columns=['col'+str(i) for i in range(num)])

Upvotes: 2

Kraigolas
Kraigolas

Reputation: 5590

Instead of adding dataframes together, let's just create a dictionary with the mappings you'd like, and create one dataframe:

data = {"col" + str(i): [] for i in range(20)}
df = pd.DataFrame(data)
#Empty DataFrame
#Columns: [col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19]
#Index: []

Upvotes: 0

Related Questions