Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

ordering each item in dataframe with python

I have a dataframe as belwo.

enter image description here

And when I sort with A and value of B (assume ascending sort in this example),

I want to have sub index of each item like this is first a, second a, as below table.

enter image description here

How can I make sub_index column like this.

Thanks in advance.

question from:https://stackoverflow.com/questions/65856940/ordering-each-item-in-dataframe-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use groupby with rank with method min to get the groupwise rankings based on smallest to largest value. Next you can sort_values by this ranking and the group.

df = pd.DataFrame({'A':['a','b','a','a','b'],'B':[100,100,120,150,200]})

df['subindex'] = df.groupby('A')['B'].rank(method='min')
df = df.sort_values(['A','subindex'])
print(df)
   A    B  subindex
0  a  100       1.0
2  a  120       2.0
3  a  150       3.0
1  b  100       1.0
4  b  200       2.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...