我试图将具有空值的列标题添加到我的数据帧中(就像这个答案一样),但是在已经对其进行了修改的函数中,如下所示:
mydf = pd.DataFrame()
def myfunc(df):
df['newcol1'] = np.nan # this works
list_of_newcols = ['newcol2', 'newcol3']
df = df.reindex(columns=df.columns.tolist() + list_of_newcols) # this does not
return
myfunc(mydf)
如果我在IPython控制台中单独运行这些行,它将添加它们。但是作为脚本运行时,将添加newcol1,但不会添加2和3。设置copy=False
也不起作用。我在这里做错了什么?
df.reindex()
除非索引相等,否则Pandas会生成一个新对象,因此您需要从函数中返回新对象。
def myfunc(df):
df['newcol1'] = np.nan # this works
list_of_newcols = ['newcol2', 'newcol3']
df = df.reindex(columns=df.columns.tolist + list_of_newcols) # this does not
return df
mydf = myfunc(mydf)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句