如何将 pandas 中的字符串替换为 int?

How to replace string to int in pandas?

我在 pandas 中有此数据,如何根据价格值将“地址”转换为数字?

    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

IIUC,你可以rank 价格是每组地址的平均价格:

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

输出:

   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

或者,如果您更喜欢组之间的密集值:

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

输出:

   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

注意。使用ascending=False参数将最高价排在第一位