如何使用熊猫修改单元格合并

时间:2019-12-10 04:33:32

标签: python excel pandas

此原始数据 之前:

| 0 | name | age | sex |
| 1 | jan  | 30  | M  |
| 2 | job | address |
| 3 | yes | 42424   | 
| 4 | name| age | sex |
| 5 | jan |  30 |  M  |
| 6 | job | address |
| 7 | yes | 42424   | 
| 8 | name| age | sex |
| 9 | jan |  30 |  M  |
|10 | job | address |
|11 | yes | 42424   | 

之后:

| 0 | name | age | sex | job | address |
| 1 | jan  | 30  |  M  | yes | 42424   |
| 2 | jan  | 30  |  M  | yes | 42424   |
| 3 | jan  | 30  |  M  | yes | 42424   |

我想在熊猫的帮助下使用Python代码更改单元格。请帮我解决一下这个。谢谢。

2 个答案:

答案 0 :(得分:0)

如果您正在寻找一种方法来使用“之前”并获得“之后”作为输入,请查看以下内容:merge row with next row in dataframe pandas

答案 1 :(得分:0)

如果格式始终相同,则仅对df和concat进行切片可能会更容易:

df = pd.DataFrame({' name ': {0: 'jan', 1: 'job', 2: 'yes', 3: 'name', 4: 'jan', 5: 'job', 6: 'yes', 7: 'name', 8: 'jan', 9: 'job', 10: 'yes'},
                   ' age ': {0: '30', 1: 'address', 2: '42424', 3: 'age', 4: '30', 5: 'address', 6: '42424', 7: 'age', 8: '30', 9: 'address', 10: '42424'},
                   ' sex ': {0: 'M', 1: nan, 2: '', 3: 'sex', 4: 'M', 5: nan, 6: '', 7: 'sex', 8: 'M', 9: nan, 10: ''}})

new_df = pd.concat([df.iloc[::4].reset_index(drop=True),
                    df.iloc[2::4,:2].reset_index(drop=True)],axis=1)

new_df.columns = ["name","age","sex","job","address"]

print (new_df)

#
  name age sex  job address
0  jan  30   M  yes   42424
1  jan  30   M  yes   42424
2  jan  30   M  yes   42424