【问题标题】:How can I delete top header and set the column names in python如何删除顶部标题并在python中设置列名
【发布时间】:2022-11-12 22:00:14
【问题描述】:

我是python新手。我的问题很简单,但我正在努力解决这个问题。

我正在使用一个简单的数据框。它有 2 列 Q 和 t。我附上了我的数据框的截图。

我想将 Q 和 t 设置为列名并删除顶部标题 (0,1)。 另一件事是为什么 df.columns 显示 rangeindex,我该如何更改它以便它支持列的名称。

我尝试了以下代码

header = df.iloc[0]
print(header)
df = df[1:]
df.columns = header
df

我得到了 Q 和 t 的第一个值作为标题名称而不是 Q 和 t。 df

我只想删除列名的索引并将 Q 和 t 设置为列名。

【问题讨论】:

标签: python pandas dataframe indexing


【解决方案1】:

在下面的代码中,我们删除了第一行并用它重命名了标题行。

# get the first row and save in variable
header = df.iloc[0]

# slice the data leaving the header row
df = df[1:]

# rename the header row as the new dataframe's header
df = df.rename(columns=header)

【讨论】:

    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2020-12-18
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多