When using a pandas dataframe, how do I add column if does not exist?

后端 未结 2 746
醉酒成梦
醉酒成梦 2021-02-06 23:01

I\'m new to using pandas and am writing a script where I read in a dataframe and then do some computation on some of the columns.

Sometimes I will have the column called

相关标签:
2条回答
  • 2021-02-06 23:34

    You check it like this:

    if 'Met' not in df:
        df['Met'] = df['freqC'] * df['coverage'] 
    
    0 讨论(0)
  • 2021-02-06 23:35

    If you were creating the dataframe from scratch, you could create the missing columns without a loop merely by passing the column names into the pd.DataFrame() call:

    cols = ['column 1','column 2','column 3','column 4','column 5']
    df = pd.DataFrame(list_or_dict, index=['a',], columns=cols)
    
    0 讨论(0)
提交回复
热议问题