【问题标题】:How to make column of ascending numbers consecutive? [duplicate]如何使升序列连续? [复制]
【发布时间】:2019-08-16 19:58:10
【问题描述】:

我有一个数据框,其中有一列按升序排列的重复数字。如何修改列,使升序的数字也连续?

我尝试了跨行的列表推导,但我需要列操作以提高性能。

d = {'col1': [1,1,1,2,2,4,4,7,7,7,50,50]}
df1 = pd.DataFrame(data=d)
df1

  col1
0   1
1   1
2   1
3   2
4   2
5   4
6   4
7   7
8   7
9   7
10  50
11  50

需要以下输出:

 col1 col2
0   1   1
1   1   1
2   1   1
3   2   2
4   2   2
5   4   3
6   4   3
7   7   4
8   7   4
9   7   4
10  50  5
11  50  5

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

使用pd.factorize:

df1['col2'] = pd.factorize(df1.col1)[0] + 1

     col1  col2
0      1     1
1      1     1
2      1     1
3      2     2
4      2     2
5      4     3
6      4     3
7      7     4
8      7     4
9      7     4
10    50     5
11    50     5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多