python - 在 Python 中映射两个集合中的值对时如何生成唯一的 id

标签 python pandas list dictionary

我有 2 列,第一列:集群,第二列:车辆

    Cluster VehicleID
435 1   2
264 1   1
444 1   1
302 1   1
191 1   1
383 1   1
81  1   1
142 2   1
6   2   1
420 2   1
153 2   1
42  2   2
168 2   1
292 2   2
138 2   2
65  2   2
316 2   1
219 2   1
329 2   1
371 3   1

基本上,这告诉集群 1 有两辆车:[1,2],集群有 1 辆车。上表是一个小样本。 所以,我有集群 1:[1,2],集群 2:[1] 我想要的是集群 1 的车辆 1 需要映射为 1,2 为 2。但是,集群 2 的车辆 1 应该映射为 3。

简而言之,它们应该是连续的,并且与“Cluster”列无关。

我不知道我哪里出了问题。 请帮忙。

最佳答案

您可以从排序开始,以便利用 diff 来查找 ID 何时更改,然后使用 cumsum 检索累积 ID。

initial = df.index

df = df.sort_values(['Cluster', 'VehicleID'])

df['new-ID'] = (df.VehicleID.diff().ne(0) | df.Cluster.diff().eq(1)).cumsum()

df.loc[initial] # back to initial ordering

     Cluster  VehicleID  new-ID
435        1          2       2
264        1          1       1
444        1          1       1
302        1          1       1
191        1          1       1
383        1          1       1
81         1          1       1
142        2          1       3
6          2          1       3
420        2          1       3
153        2          1       3
42         2          2       4
168        2          1       3
292        2          2       4
138        2          2       4
65         2          2       4
316        2          1       3
219        2          1       3
329        2          1       3
371        3          1       5

关于python - 在 Python 中映射两个集合中的值对时如何生成唯一的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504572/

相关文章:

python - 如何生成已知月份的天数列表

python - 如何使用下拉列表更新多个图形的 y 轴列?

python - 如何将 'or' 应用于 Python 中列表的所有值?

python - Pandas 计算多列数据中列减去的平均值

python - 将两个数字数据框列组合成一列元组

python - list.append 的意外行为

python - in 语句仅对 python 中的列表起作用一次

python - 使用 Map-Reduce 进行排序 - 可能的方法

python - 与 Pandas 的参差不齐的转置

list - 如何从Prolog中的列表中删除最后一个元素?