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

pandas - add dense rank in python dataframe where all the columns are in string

how can i add rank column in dataframe in pandas where all the columns of dataframe datatype in string.to achive the following output group by condition based on col1 & col2. trying to create column RANK(which will work as dnese rank same like sql).

df = pd.DataFrame({
'Col1' : ['A1',"A1","A1","A1","A1","A1","A2","A2","A2","A2","A2","A2","A4","A4","A5","A5","A5"],
'Col2' : ['B1',"B1","B1","B2",'B3',"B4","B1","B1",'B2',"B2","B2","B3","B3","B1","B1","B2","B3"],
'Col3' : ['A101',"A102","A103","A104",'A105',"A106","A107","A108","A109","A110","A111","A112","A113","A114","A115","A116","A117"]
})
df

enter image description here

question from:https://stackoverflow.com/questions/65623384/add-dense-rank-in-python-dataframe-where-all-the-columns-are-in-string

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

1 Answer

0 votes
by (71.8m points)

Try:

df['RANK'] = df.groupby(['Col1','Col2']).cumcount() + 1

Output:

   Col1 Col2  Col3  RANK
0    A1   B1  A101     1
1    A1   B1  A102     2
2    A1   B1  A103     3
3    A1   B2  A104     1
4    A1   B3  A105     1
5    A1   B4  A106     1
6    A2   B1  A107     1
7    A2   B1  A108     2
8    A2   B2  A109     1
9    A2   B2  A110     2
10   A2   B2  A111     3
11   A2   B3  A112     1
12   A4   B3  A113     1
13   A4   B1  A114     1
14   A5   B1  A115     1
15   A5   B2  A116     1
16   A5   B3  A117     1

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

...