如何在Python中排列数据框的列 [英] How to Arrange a column of a Dataframe in Python
本文介绍了如何在Python中排列数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有值的数据框
I have a dataframe with values
Product Range Sold
A 1-3 5
A 4-7 23
A 8-15 2
B 4-7 4
B 8-15 1
我需要输出为
Sold
Product Range
A 1-3 5
4-7 23
8-15 2
B 4-7 4
8-15 1
这可以通过任何内置函数或数据透视表函数来完成吗?
Can this be done by any built-in functions or any pivot table functions?
推荐答案
If need MultiIndex
use set_index
:
df = df.set_index(['Product','Range'])
如果未对第一级进行排序,请使用 mask
和 duplicated
:
If not and first level is sorted, use mask
with duplicated
:
df['Product'] = df['Product'].mask(df['Product'].duplicated(), '')
print (df)
Product Range Sold
0 A 1-3 5
1 4-7 23
2 8-15 2
3 B 4-7 4
4 8-15 1
这篇关于如何在Python中排列数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文