1

If I have a df such as this:

   a  b
0  1  3
1  2  4

I can use df['c'] = '' and df['d'] = -1 to add 2 columns and become this:

   a  b c  d
0  1  3   -1
1  2  4   -1

How can I make the code within a function, so I can apply that function to df and add all the columns at once, instead of adding them one by one seperately as above? Thanks

7
  • do you know all the values that correspond to the column names? I'm wondering why you may want to do this. Commented Dec 18, 2019 at 22:11
  • @MattR The values are either n/a, or with a bool value, just a default value. Because I want to create a function specifically for adding columns. But I have no idea how to do that for dataframe. Commented Dec 18, 2019 at 22:17
  • 1
    df = df.assign(**{'c':1,'d':2}) - or df.assign(c=1,d=2) ... pandas.pydata.org/pandas-docs/stable/reference/api/… Commented Dec 18, 2019 at 22:19
  • Sorry, I want to create a function so it can be used to add columns for different dfs. Is that a way to do that? Commented Dec 18, 2019 at 22:24
  • Does this answer your question? adding multiple columns to pandas simultaneously Commented Dec 18, 2019 at 22:25

2 Answers 2

2

Create a dictionary:

dictionary= { 'c':'', 'd':-1 }

def new_columns(df, dictionary):
    return df.assign(**dictionary)

then call it with your df:

df = new_columns(df, dictionary)

or just ( if you don't need a function call, not sure what your use case is) :

df.assign(**dictionary)
Sign up to request clarification or add additional context in comments.

3 Comments

why we need a function here ? df.assign(**dictionary)?
OP wants a function, so that's why i answered with one
assign is a function itself
0
def update_df(a_df, new_cols_names, new_cols_vals):
  for n, v in zip(new_cols_names, new_cols_vals):
    a_df[n] = v

update_df(df, ['c', 'd', 'e'], ['', 5, 6])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.