Home > Blockchain >  How to replace string to int in pandas?
How to replace string to int in pandas?

Time:10-24

I have this data in pandas and how can I convert "Address" to a number according to the price value?

    Area    Room    Parking    Address          Price
0   63       1      1          Shahran          1850000000
1   60       1      1          Chids            1850000000
2   79       2      1          Pardis           550000000
3   95       2      1          Shahrake         902500000
4   123      2      1          Shahrake         7000000000

CodePudding user response:

IIUC, you can rank the prices by the mean Price per group of Address:

df['rank'] = df.groupby('Address')['Price'].transform('mean').rank()

output:

   Area  Room  Parking   Address       Price  rank
0    63     1        1   Shahran  1850000000   2.5
1    60     1        1     Chids  1850000000   2.5
2    79     2        1    Pardis   550000000   1.0
3    95     2        1  Shahrake   902500000   4.5
4   123     2        1  Shahrake  7000000000   4.5

Or if you prefer dense values between groups:

df['rank'] = df.groupby('Address')['Price'].transform('mean').rank(method='dense')

output:

   Area  Room  Parking   Address       Price  rank
0    63     1        1   Shahran  1850000000     2
1    60     1        1     Chids  1850000000     2
2    79     2        1    Pardis   550000000     1
3    95     2        1  Shahrake   902500000     3
4   123     2        1  Shahrake  7000000000     3

NB. use the ascending=False parameter to rank the highest price first

  • Related