How to dinamically add columns in exist dataframe?

Viewed 21

I have a dataframe with fixed columns count: A B C D E MMYY

Dataframe is created like this:

pd.DataFrame(colsValue)

Also there is a full list of colums names: [A,B,C,D,E, MMYY, AGE, COUNTRY]

How to create additional columns in dataframe and fill them by rest from full list.

Initial dataset looks like:

A B C D E 
1 2 3 4 5

After should looks

A B C D E MMYY AGE COUNTRY 
1 2 3 4 5 Null Null Null
 

Base solution below:

for dfName, df in dict_of_dfs.items():
    report[dfName] = {}
   
    allcols = dict_of_dfs_columns_names[dfName] + [x for x in allColumnsNames if x not in dict_of_dfs_columns_names[dfName]]
    print(allcols)
    df = df.reindex(allcols, axis=1)
    df.astype({'CCUNM':'int64'})

I got this error:

IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer

On the line:

 df.astype({'CCUNM':'int64'})
1 Answers

You can try reindex

l = ['A','B','C','D','E', 'MMYY', 'AGE', 'COUNTRY']

df = df.reindex(l, axis=1)
print(df)

   A  B  C  D  E  MMYY  AGE  COUNTRY
0  1  2  3  4  5   NaN  NaN      NaN
Related