close

How to add multiple columns to pandas dataframe in one assignment?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to add multiple columns to pandas dataframe in one assignment in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to add multiple columns to pandas dataframe in one assignment?

  1. How to add multiple columns to pandas dataframe in one assignment?

    if adding a lot of missing columns (a, b, c ,….) with the same value, here 0, i did this:

  2. add multiple columns to pandas dataframe in one assignment

    if adding a lot of missing columns (a, b, c ,….) with the same value, here 0, i did this:

Method 1

You could use assign with a dict of column names and values.

In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
   col_1  col_2 col2_new_2  col3_new_3  col_new_1
0      0      4       dogs           3        NaN
1      1      5       dogs           3        NaN
2      2      6       dogs           3        NaN
3      3      7       dogs           3        NaN

Method 2

if adding a lot of missing columns (a, b, c ,….) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It’s based on the second variant of the accepted answer.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read