合并 Pandas 中两行的内容

guy*_*yts 4 python dataframe pandas

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

0   eye-right   eye-right   hand
1   location    location    position
2   12          27.7        2
3   14          27.6        2.2
Run Code Online (Sandbox Code Playgroud)

我希望它变成:

0   eye-right_location   eye-right_location   hand_position
1   12                   27.7                 2
2   14                   27.6                 2.2
Run Code Online (Sandbox Code Playgroud)

最终我想将第 0 行转换为标题,并为整个 df 重置索引。

jpp*_*jpp 6

您可以设置列标签,通过 切片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
Run Code Online (Sandbox Code Playgroud)