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
287 views
in Technique[技术] by (71.8m points)

python - how to re rank after drop a row in data in pandas

I have a data result from recommender system like this for example

id          content_id       Rank
08773338    aaaa              1
08773338    bbbb              2
08773338    cccc              3
08333777    bbbb              1
08333777    aaaa              2
08333777    cccc              3

then I want to drop 'bbbb' content id so that it becomes like this

for example

id          content_id       Rank
08773338    aaaa              1
08773338    cccc              3
08333777    aaaa              2
08333777    cccc              3

How do I re-rank the rank column after the bbbb label is removed?

like this

id          content_id       Rank
08773338    aaaa              1
08773338    cccc              2
08333777    aaaa              1
08333777    cccc              2

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

1 Answer

0 votes
by (71.8m points)

You can use groupby.rank after masking/subsetting the dataframe:

u = df[df['content_id'].ne("bbbb")].copy()
u['Rank'] = u.groupby("id")['Rank'].rank(method='dense')#.reset_index(drop=True)

print(u)
        id content_id  Rank
0  8773338       aaaa   1.0
2  8773338       cccc   2.0
4  8333777       aaaa   1.0
5  8333777       cccc   2.0

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

...