【问题标题】:How to modify using pandas to cell merge如何使用 pandas 修改单元格合并
【发布时间】:2019-12-10 04:33:32
【问题描述】:

这个原始数据 之前:

| 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   |

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

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果格式始终相同,只对 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-26
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2019-08-06
        相关资源
        最近更新 更多