python - 如何将列标题设置为 Pandas 数据框中的第一行?

标签 python pandas dataframe

如何将数据框的列标题设置为数据框的第一行并重置列名?

# Creation of dataframe

df = pd.DataFrame({"A": ["1", "4", "7"],
                   "B": ["2", "5", "8"],
                   "C": ['3','6','9']})

# df:

   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

期望的结果:

   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

最佳答案

使用concatIndex.to_frame对一行 DataFrame 进行转置,最后按 range 设置列名:

df = pd.concat([df.columns.to_frame().T, df], ignore_index=True)
df.columns = range(len(df.columns))
print (df)
   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

或者使用DataFrame.set_axis对于链式方法解决方案:

df = (pd.concat([df.columns.to_frame().T, df], ignore_index=True)
        .set_axis(range(len(df.columns)), axis=1))

关于python - 如何将列标题设置为 Pandas 数据框中的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70617982/

相关文章:

Python:排除模块 Pyinstaller

python - python 中未识别错误名称

python - 数据帧上的 ArrowNotImplementedError : halffloat error on applying pandas. to_feather

python - 如何组合 Pandas 系列

r - 从 R 中的向量中累积选取元素

python - 基于多条件检查将值放在另一个数据框中的 pandas 数据框中的列中

python - 如何比较两列的值并根据比较对值重新排序

Python - BeautifulSoup - 通过列表中的特定元素遍历 findall

python - 如何对测试数据使用逻辑回归

python - 值错误: Location based indexing can only have [labels (MUST BE IN THE INDEX)