首页 > 解决方案 > 合并熊猫中两行的内容

问题描述

我有一个数据框,我想在其中合并两行的内容,并在同一个单元格中用下划线分隔。如果这是原始 DF:

0   eye-right   eye-right   hand
1   location    location    position
2   12          27.7        2
3   14          27.6        2.2

我希望它变成:

0   eye-right_location   eye-right_location   hand_position
1   12                   27.7                 2
2   14                   27.6                 2.2

最终我想将第 0 行翻译成标题,并重置整个 df 的索引。

标签: pythonpandasdataframe

解决方案


您可以设置列标签,通过切片iloc,然后reset_index

print(df)
#            0          1         2
# 0  eye-right  eye-right      hand
# 1   location   location  position
# 2         12       27.7         2
# 3         14       27.6       2.2

df.columns = (df.iloc[0] + '_' + df.iloc[1])
df = df.iloc[2:].reset_index(drop=True)

print(df)
#   eye-right_location eye-right_location hand_position
# 0                 12               27.7             2
# 1                 14               27.6           2.2

推荐阅读