【问题标题】:Pandas does not show first column [duplicate]熊猫不显示第一列[重复]
【发布时间】:2022-01-16 03:18:55
【问题描述】:

我有几个函数可以过滤不同客户特征的数据框并返回过滤后的数据框,如下所示:

stg_1 = strategy_1_filtering(df_1)
stg_2 = strategy_2_filtering(df_2)

现在,我根据客户 ID 和策略制作一个邻接矩阵:

d = {'stg_1':stg_1['Customer_ID'],'stg_2':stg_2['Customer_ID']}
df  = pd.DataFrame({k: dict.fromkeys(v, True) for k, v in d.items()}).fillna(False)

结果是这样的:

stg_1 stg_2
385986.0 True True
363015.0 True False
411847.0 True True
413369.0 True True
401081.0 True False

我已尝试使用此代码更改第一列的名称:

 df.columns.values[0] = "Customer_ID"

但它没有工作。为了理解我打印了数据框的形状和列名的问题:

print(df.shape)
print(df.columns)

结果:

(1155, 2)
Index(['stg_1', 'stg_2'], dtype='object')

在这种情况下,当数据框连第一列都检测不到时,我该怎么办?

【问题讨论】:

    标签: python pandas rename


    【解决方案1】:

    您的第一列实际上是一个索引。使用rename_axis:

    df = df.rename_axis('Customer ID')
    

    如果要将索引作为列,请使用reset_index:

    df = df.rename_axis('Customer ID').reset_index()
    

    【讨论】:

      【解决方案2】:

      我假设您的 第一列 实际上是 DataFrame 的 index。 命名:

      df.index.name = "Customer_ID"
      

      【讨论】:

        猜你喜欢
        • 2019-04-11
        • 2021-08-12
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 2020-04-09
        • 1970-01-01
        相关资源
        最近更新 更多