Julio Gomez
Julio Gomez

Reputation: 35

Adding a group of headers to an existing dataframe

I need to append a group of additional headers (as blank columns) to an existing dataframe; the corresponding values will be added in a later process. Please, advise, thanks!

Upvotes: 2

Views: 140

Answers (2)

jpp
jpp

Reputation: 164643

You can use pd.DataFrame.join with a dataframe consisting of empty columns:

cols_to_add = list('abcde')
df = df.join(pd.DataFrame(columns=cols_to_add))

Upvotes: 2

ALollz
ALollz

Reputation: 59529

Here's one way, I've included some sample data.

import pandas as pd
df = pd.DataFrame({'c1': [1, 2, 3],
                   'c2': [1, 1, 1],
                   'c3': ['a', 'b', 'c'],
                   'c4': ['a', 'a', 'a'],
                   'cat': ['x', 'x', 'y']})

# These are the column headers you want to add
cols_to_add = ['a', 'b', 'c', 'd', 'e']

Code:

df = df.assign(**dict((col, '') for col in cols_to_add))

Output:

   c1  c2 c3 c4 cat a b c d e
0   1   1  a  a   x          
1   2   1  b  a   x          
2   3   1  c  a   y          

Explanation: DataFrame.assign allows you to assign columns to the DataFrame. You can pass it an unpacked dictionary as keyword arguments to assign multiple columns at once, in this case with the column name given by the names in our list, and the values as the empty string.

Upvotes: 0

Related Questions