python - Pandas 根据列中的值将字符串映射到 int

标签 python pandas dataframe

我有一个包含两列的数据框:

state  total_sales
AL      16714
AR      6498
AZ      107296
CA      33717

现在我想根据 total_sales 中值的递增顺序将 state 列中的字符串映射到从 1 到 N 的 int(其中 N 是行数,此处为 4 )。结果应存储在另一列(例如标签)中。也就是说,想要这样的结果:

state  total_sales label
AL      16714         3
AR      6498          4
AZ      107296        1
CA      33717         2

请建议矢量化实现。

最佳答案

您可以使用 rank强制转换为 int:

df['label'] = df['total_sales'].rank(method='dense', ascending=False).astype(int)
print (df)
  state  total_sales  label
0    AL        16714      3
1    AR         6498      4
2    AZ       107296      1
3    CA        33717      2

关于python - Pandas 根据列中的值将字符串映射到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42330624/

相关文章:

r - 如何返回 R 中两个 data.frames 之间匹配行的索引

python - 字典的稀疏数组 - 高效表示

鼠标悬停在 Tkinter 窗口上时 python 内核崩溃

python - 如何根据 Pandas 中的另一列聚合一列

python - 使用从两个列表中提取的两个变量迭代连接到 API 的一段代码

python - 如何仅在特定时间间隔内增加值(value)python

python - Cartopy:绘制网格线标签,但不绘制网格线本身

Python长格式: subtract selection of rows

python - Pandas 连续日期

python - 如何在 Python 中动态命名数据框?