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

saga
  • 736
  • 2
  • 8
  • 20
  • do you know all the values that correspond to the column names? I'm wondering why you may want to do this. – MattR Dec 18 '19 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. – saga Dec 18 '19 at 22:17
  • 1
    `df = df.assign(**{'c':1,'d':2})` - or `df.assign(c=1,d=2)` ... https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html?highlight=assign – wwii Dec 18 '19 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? – saga Dec 18 '19 at 22:24
  • Does this answer your question? [adding multiple columns to pandas simultaneously](https://stackoverflow.com/questions/39050539/adding-multiple-columns-to-pandas-simultaneously) – wwii Dec 18 '19 at 22:25
  • Make a function that takes a DataFrame and a dictionary as arguments; in the function add the new columns; return the new DataFrame. – wwii Dec 18 '19 at 22:27
  • Could you provide some more context for this? – AMC Dec 19 '19 at 00:02

2 Answers2

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)
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
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])
Samer Ayoub
  • 981
  • 9
  • 10