How to add an empty column to a dataframe?

后端 未结 11 650
自闭症患者
自闭症患者 2020-11-28 01:06

What\'s the easiest way to add an empty column to a pandas DataFrame object? The best I\'ve stumbled upon is something like

df[\'foo\'] = df.ap         


        
11条回答
  •  伪装坚强ぢ
    2020-11-28 01:16

    Sorry for I did not explain my answer really well at beginning. There is another way to add an new column to an existing dataframe. 1st step, make a new empty data frame (with all the columns in your data frame, plus a new or few columns you want to add) called df_temp 2nd step, combine the df_temp and your data frame.

    df_temp = pd.DataFrame(columns=(df_null.columns.tolist() + ['empty']))
    df = pd.concat([df_temp, df])
    

    It might be the best solution, but it is another way to think about this question.

    the reason of I am using this method is because I am get this warning all the time:

    : SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      df["empty1"], df["empty2"] = [np.nan, ""]
    

    great I found the way to disable the Warning

    pd.options.mode.chained_assignment = None 
    

提交回复
热议问题