Adding new column to existing DataFrame in Python pandas

后端 未结 25 1297
你的背包
你的背包 2020-11-22 01:15

I have the following indexed DataFrame with named columns and rows not- continuous numbers:

          a         b         c         d
2  0.671399  0.101208 -         


        
25条回答
  •  無奈伤痛
    2020-11-22 01:46

    I got the dreaded SettingWithCopyWarning, and it wasn't fixed by using the iloc syntax. My DataFrame was created by read_sql from an ODBC source. Using a suggestion by lowtech above, the following worked for me:

    df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))
    

    This worked fine to insert the column at the end. I don't know if it is the most efficient, but I don't like warning messages. I think there is a better solution, but I can't find it, and I think it depends on some aspect of the index.
    Note. That this only works once and will give an error message if trying to overwrite and existing column.
    Note As above and from 0.16.0 assign is the best solution. See documentation http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html#pandas.DataFrame.assign Works well for data flow type where you don't overwrite your intermediate values.

提交回复
热议问题