python - 如何在函数内重新索引 pandas 数据框?

标签 python pandas dataframe reindex

我正在尝试将具有空值的列标题添加到我的数据帧( just like this answer ),但在已经修改它的函数内,如下所示:

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也不起作用。我在这里做错了什么?

最佳答案

Pandas df.reindex()除非索引相等,否则会生成一个新对象,因此您需要从函数中返回新对象。

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)

关于python - 如何在函数内重新索引 pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54220501/

相关文章:

python - 在 64 位平台上使用 python 32 位

python - 我可以使用 lambdify 来评估 python 函数的导数吗?

python - cv2.videowriter 写入 0 字节文件 (python) (opencv)

python - 'DataFrame' 对象没有属性 'types'

python - pandas groupby 两个相似的列和两个不同的列

r - 使用 diff 函数和 mutate at from dplyr

python - 为什么同一类的两个实例具有不同的属性(Python)是明智的?

python - 通过旋转多列来 reshape DataFrame

python - 使用具有公共(public)键的两个查询的结果来创建数据框,而无需使用合并

python - 将 1 分钟间隔内的最后一个值分配给 pandas DataFrame 的行