1

I have a dataframe that looks like 1000 rows, 10 columns

I want to add 20 columns with only one single value in each column (what I call a default value)

Therefore, my final df would be 1000 rows, with 30 columns

I know that I can do it 30 times by doing:

df['column 11'] = 'default value'
df['column 12'] = 'default value 2'

But I would like to do it in a proper way of coding

I have a dict with my {'column label' : 'defaultvalues'}

How can I do so ?

I've tried pd.insert or pd.concatenate but couldn't find my way through

thanks

regards,

Eric

1
  • 4
    df.assign(**some_dict_mapping_label_to_value). Commented Apr 18, 2019 at 12:57

2 Answers 2

2

One way to do so:

df_len = len(df)
new_df = pd.DataFrame({col: [val] * df_len for col,val in your_dict.items()})
df = pd.concat((df,new_df), axis=1)
Sign up to request clarification or add additional context in comments.

Comments

1

Generally if possible spaces in keys in dictionary for new columns names use DataFrame constuctor with DataFrame.join:

df = pd.DataFrame({'a':range(5)})
print (df)
   a
0  0
1  1
2  2
3  3
4  4

d = {'A 11' : 's', 'A 12':'c'}
df = df.join(pd.DataFrame(d, index=df.index))
print (df)
   a A 11 A 12
0  0    s    c
1  1    s    c
2  2    s    c
3  3    s    c
4  4    s    c

If no spaces and no numbers in columns names (need valid identifier) is possible use DataFrame.assign:

d = {'A11' : 's', 'A12':'c'}
df = df.assign(**d)
print (df)
   a A11 A12
0  0   s   c
1  1   s   c
2  2   s   c
3  3   s   c
4  4   s   c

Another solution is loop by dictionary and assign:

for k, v in d.items():
    df[k] = v

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.