python - 合并熊猫中两行的内容
问题描述
我有一个数据框,我想在其中合并两行的内容,并在同一个单元格中用下划线分隔。如果这是原始 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 的索引。
解决方案
您可以设置列标签,通过切片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
推荐阅读
- ruby - 如何在 Ruby 中使用哈希键进行这些字符串替换?
- php - 在 Laravel 中按计数排序
- python - 如何使用 np.fromregex 很好地读取数据?
- r - 无法将功能应用于数据框
- python-3.x - 绘制一个信号时,axvline 图不可见 - matplotlib python
- postgresql - 使用 JOOQ 获取 Postgres UDT 值
- excel - 发送电子邮件后设置提醒
- angular - 如何让现场发球更快?
- python - opencv 导入错误(libopencv_dnn.so.3.4 未定义符号)
- ms-access - Access查询中的计数/分组记录