how do i set columns in a dataframe even when one of the columns doesn’t exist?

You can do something like this:

import numpy as np
import pandas as pd

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
df_t = pd.DataFrame(data)

final_columns = ['col_1', 'col_2', 'col_3']

for col in final_columns:
   if col not in df_t.columns:
      df_t[col] = np.NaN

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top