【问题标题】:can´t rename column of dataframe which is created from numpy array无法重命名从 numpy 数组创建的数据框列
【发布时间】:2020-03-08 11:15:09
【问题描述】:

我从一个 numpy 数组创建了一个 pd.dataframe,数组的单列的标题是“0”,我想重命名此列,对我来说是在数组中重命名还是仅重命名无关紧要将其转换为数据框后。

theor_power_output         =np.interp(wind_speed, power_curve_wind_speeds, power_curve_values, left=0, right=0)
tpo                        =pd.DataFrame(theor_power_output)
tpo.rename(columns={'0':'TheorPwr'}, inplace=True)

由于 df.rename 在同一代码中处理另一个数据帧,我猜它与 numpy-array 的标头有关。任何帮助,将不胜感激。

【问题讨论】:

  • 您遇到的错误是什么?它可能是0 而不是'0'
  • numpy 数组没有标头。使用简单的二维数组参数,pandas 只需分配数字索引[0,1,2...]。使用columns 参数。
  • 感谢您的帮助。我使用assign 方法规避了这个问题。在这种情况下,我可以将数组分配给具有我想要的列名的数据框。
  • 试试tpo.rename(columns={0:'TheoPwr'}, inplace=True)

标签: python pandas numpy spyder


【解决方案1】:

在这种情况下,您应该从打印列名开始 在有问题的 DataFrame 中:

print(tpo.columns)

或者,如果你使用例如Jupyter Notebook,只需tpo.columns

那么您肯定会注意到列名只是 连续的数字(不是字符字符串)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2017-12-01
    • 1970-01-01
    • 2020-04-28
    • 2018-11-04
    • 1970-01-01
    • 2011-01-07
    • 2016-12-18
    相关资源
    最近更新 更多