How to add multiple columns to pandas dataframe in one assignment

0 votes

I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps.

import pandas as pd

df = {'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)

df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3]  #thought this wo
Jun 15, 2020 in Python by kartik
• 37,520 points
15,874 views

1 answer to this question.

0 votes

Hello @kartik,

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

Hope it helps!!

answered Jun 15, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to convert multiple columns to string in pandas dataframe?

Hi, To convert multiple columns to string, include a list of ...READ MORE

answered Jul 19, 2019 in Python by Taj
• 1,080 points
27,798 views
+1 vote
1 answer

How to change the order of DataFrame columns in pandas?

Hi@akhtar, You can rearrange a DataFrame object by ...READ MORE

answered Oct 20, 2020 in Python by MD
• 95,460 points
836 views
0 votes
1 answer

How to combine two columns of text in pandas dataframe?

If both columns are strings, you can ...READ MORE

answered Jan 5, 2021 in Python by Gitika
• 65,890 points
1,928 views
0 votes
1 answer

How to convert a Pandas GroupBy object to DataFrame in Python

g1 here is a DataFrame. It has a hierarchical index, ...READ MORE

answered Nov 12, 2018 in Python by Nymeria
• 3,560 points
34,419 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,391 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,995 views
+1 vote
3 answers

How to change/update cell value in Python Pandas dataframe?

You can use the at() method to ...READ MORE

answered Apr 8, 2019 in Python by Kunal
147,286 views
0 votes
1 answer

How to check if any value is NaN in a Pandas DataFrame?

Hello @kartik, If you need to know how ...READ MORE

answered Jun 15, 2020 in Python by Niroj
• 82,880 points
4,239 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP