【问题标题】:categorize numerical series with python用python对数字序列进行分类
【发布时间】:2018-05-15 17:32:45
【问题描述】:

我正在研究如何从不断增加的枚举列中分配分类。这是我的数据框的一个示例:

df = pd.DataFrame({'A':[1,1,1,1,1,1,2,2,3,3,3,3,3],'B':[1,2,3,12,13,14,1,2,5,6,7,8,50]})

这个产品:

df
Out[9]: 
    A   B
0   1   1
1   1   2
2   1   3
3   1  12
4   1  13
5   1  14
6   2   1
7   2   2
8   3   5
9   3   6
10  3   7
11  3   8
12  3  50

B 列的数字系列不断增加,但有时系列会中断并继续使用其他数字或重新开始。我想要的输出是:

Out[11]: 
    A   B  C
0   1   1  1
1   1   2  1
2   1   3  1
3   1  12  2
4   1  13  2
5   1  14  2
6   2   1  3
7   2   2  3
8   3   5  3
9   3   6  4
10  3   7  4
11  3   8  4
12  3  50  5

I appreciate your suggestions, because I can not find an ingenious way to 

去做吧。谢谢

【问题讨论】:

    标签: python pandas enumerate


    【解决方案1】:

    这是你需要的吗?

    df.B.diff().ne(1).cumsum()
    Out[463]: 
    0     1
    1     1
    2     1
    3     2
    4     2
    5     2
    6     3
    7     3
    8     4
    9     4
    10    4
    11    4
    12    5
    Name: B, dtype: int32
    

    【讨论】:

    • 你让它看起来很简单!赞赏!
    • @JonathanPacheco yw :-) 快乐编码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多