pandas 将单元格与熊猫合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47684606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:52:02  来源:igfitidea点击:

Merge cells with pandas

pythonpandas

提问by yigitozmen

I want to remove duplicated cells with merge them all because they point out subelements. For example I have a df like this:

我想删除重复的单元格并合并它们,因为它们指出了子元素。例如,我有一个这样的 df:

|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 | HETO90      | Baby Sets     |  1000.0 |
| 1 | HETO90      | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 | HETO90      | Girls Top     | 13398.0 |
| 4 | HETO90      | Shorts        |  7590.0 |

I just want to merge HET090 to the one. Like this:

我只想将 HET090 合并到一个。像这样:

|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 |             | Baby Sets     |  1000.0 |
| 1 |             | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 |             | Girls Top     | 13398.0 |
| 4 |             | Shorts        |  7590.0 |

回答by Scott Boston

In pandas the inner most index must label each row.

在Pandas中,最里面的索引必须标记每一行。

df = df.set_index('Customer ID', append=True).swaplevel(0,1)

Output:

输出:

                    Category    VALUE
Customer ID                          
HETO90      0      Baby Sets   1000.0
            1  Girls Dresses   5356.0
            2  Girls Jumpers   2822.0
            3      Girls Top  13398.0
            4         Shorts   7590.0