【问题标题】:How do I remove the index numbers above the column names in pandas?如何删除熊猫中列名上方的索引号?
【发布时间】:2021-12-18 06:56:36
【问题描述】:

当我将 Google 表格中的数据提取到 pandas 数据框中时,我遇到了问题。当我调用数据框时,我会在列名上方看到数字。

这是我迄今为止尝试过的:

df = df.rename_axis(None)
df.rename_axis(None, axis = 1)
df = df.reset_index(drop=True)
del df.index.name
df = df.iloc[1: , :]

这些都没有删除列上方的这些数字。有没有人有其他的删除建议?

当我输入print(df.columns) 时,结果是:

RangeIndex(start=0, stop=10, step=1)

当我print(df.iloc[0, :]) 时,结果是:

0                            Day
1                       Currency
2                          Spend
3              Total Order Value
4            CVR (Click through)
5                         Clicks
6                    Impressions
7                            CTR
8                            CPC
9    Conversions (Click through)
Name: 0, dtype: object

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    由于您没有提供可执行代码 sn-p,因此很难确定,但从您提供的图像看来,列名似乎已出现在数据帧的第一行。可以推断出这是因为第一行索引 (0) 与您要用作列名的字符串值对齐。

    顶部的索引号实际上是(默认)列名。

    您可以通过执行以下操作来确认这一点:

    print(df.columns)  # This will print the actual column names
    print(df.iloc[0, :])  # This will print the first row of values
    

    您能否将这些语句的输出添加到您的问题中?一旦我们确认了这一点,我们就可以考虑如何解决这个问题。

    如果我的诊断正确,您可以查看this answer 了解如何解决问题。

    【讨论】:

      【解决方案2】:

      我相信问题出在您读取 csv 文件时。 Pandas 假设顶部的这些数字是您的标题(实际上它是您的第一行)我可以建议 2 个修复。

      第一个是告诉熊猫你的标题实际上是你的第一行

      df = pd.read_csv("PATH", header=1)
      

      第二个和第一个非常相似,但是你告诉 pandas 跳过第一行

      df = pd.read_csv("PATH", skiprows=1)
      

      【讨论】:

        猜你喜欢
        • 2015-06-28
        • 2020-01-04
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        • 2017-11-21
        相关资源
        最近更新 更多