【问题标题】:Rearrange dataframe valuesRearrange dataframe values
【发布时间】:2022-12-02 00:46:42
【问题描述】:

Let's say I have the following dataframe:

     ID              stop        x           y           z
0    202             9           20          27          4 
1    202             2           23          24          13
2    1756            5           5           41          73
3    1756            3           7           42          72 
4    1756            4           3           50          73    
5    2153            14          121         12          6    
6    2153            3           122.5       2           6   
7    3276            1           54          33          -12 
8    5609            9           -2          44          -32
9    5609            2           8           44          -32
10   5609            5           102         -23         16

I would like to change the ID values in order to have the smallest being 1, the second smallest being 2 etc.. So for my example, I would get this:

     ID              stop        x           y           z
0    1               9           20          27          4 
1    1               2           23          24          13
2    2               5           5           41          73
3    2               3           7           42          72 
4    2               4           3           50          73    
5    3               14          121         12          6    
6    3               3           122.5       2           6   
7    4               1           54          33          -12 
8    5               9           -2          44          -32
9    5               2           8           44          -32
10   5               5           102         -23         16

Any idea please?

Thanks in advance!

【问题讨论】:

  • Your two dataframes are identical.
  • Sorry I've revised the second one.
  • pandas.Series.rank

标签: python pandas dataframe


【解决方案1】:

You can use pd.Series.rank with method='dense'

df['ID'] = df['ID'].rank(method='dense').astype(int)

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2022-12-01
    • 1970-01-01
    • 2022-11-09
    • 2022-12-02
    • 2013-11-26
    • 1970-01-01
    • 2022-12-28
    • 2015-02-24
    相关资源
    最近更新 更多