【问题标题】:Pandas: Name the unmaed column of dataframePandas:命名数据框的未删除列
【发布时间】:2020-02-24 05:16:39
【问题描述】:

我的数据框只有一列,但没有任何名称,如下图所示。

现在我想命名未命名的列。我查看了现有线程(Rename unnamed column pandas dataframe)并编写了以下代码:

temp.rename(columns = {0:'SUBGROUP'},inplace=True)

但它没有产生预期的结果。谁能指出我在哪里犯了错误?

【问题讨论】:

  • 对我来说看起来像 Series,而不是 DataFrame
  • 感谢您指出问题。确实是一个系列。谢谢

标签: python python-3.x pandas


【解决方案1】:

首先需要明确Pandas Series是一维数据,Series name就是你想要的列名,打印的时候显示在下方。如果想要得到期望的列名出现在列值上方的效果,则必须将数据类型转换为 pandas 的 DataFrame 类型。


演示

import pandas as pd

# build Series temp with first 3 row data of your example
temp = pd.Series(data=["DA33", "", "FK33-2"], index=[70015,69999, 69998])
temp.index.name = "SITE_NUMBER"
temp.name = "FEEDERID"
print(type(temp))
print(temp)

# transform type from Series to DataFrame
# you see the name of Series should beoome the column name of DataFrame
temp = pd.DataFrame(data=temp)
print(type(temp))
print(temp)

【讨论】:

  • @user2293224,pandas Series是一维数据,所以没有列的概念。此时Series的名字就是你想要的列名,打印的时候会出现在下面。如果要使用列的概念,即列名出现在列值的上方供以后数据挖掘,必须先将数据类型转换为pandas的dataFrame类型。
猜你喜欢
  • 2021-12-06
  • 2017-10-14
  • 2019-06-07
  • 2022-10-23
  • 2021-12-20
  • 2018-04-29
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
相关资源
最近更新 更多