【问题标题】:python pandas\numpy encode unique by integers [duplicate]python pandas\numpy按整数编码唯一[重复]
【发布时间】:2016-04-19 18:20:27
【问题描述】:

假设我有 x=["apple","orange","orange","apple","pear"] 我想要一个带有整数的分类表示,例如y=[1,2,2,1,3]。最好的方法是什么?

【问题讨论】:

  • 整数代表什么?
  • 大概你检查了docs
  • 如果您正在使用 numpy,您可以直接使用 np.unique(["apple","orange","orange","apple","pear"], return_inverse=True)[1],而无需使用 pandas

标签: python pandas integer unique categorical-data


【解决方案1】:

您可以使用 pd.factorize 并为此使用字段 0:

In [465]: pd.factorize(x)
Out[465]: (array([0, 1, 1, 0, 2]), array(['apple', 'orange', 'pear'], dtype=object))

In [466]: pd.factorize(x)[0] + 1
Out[466]: array([1, 2, 2, 1, 3])

【讨论】:

    【解决方案2】:

    你可以使用:

    import pandas as pd
    
    x=["apple","orange","orange","apple","pear"]
    s = pd.Series(x)
    
    print s
    
    0     apple
    1    orange
    2    orange
    3     apple
    4      pear
    
    print pd.Categorical(s).codes
    
    [0 1 1 0 2]
    

    或者:

    import pandas as pd
    
    x=["apple","orange","orange","apple","pear"]
    
    print pd.Categorical(x).codes
    
    #[0 1 1 0 2]
    

    【讨论】:

      【解决方案3】:

      与熊猫:x.astype('category').cat.codes

      【讨论】:

        猜你喜欢
        • 2018-02-18
        • 2019-02-16
        • 1970-01-01
        • 2012-09-24
        • 2012-10-07
        • 2016-11-30
        • 1970-01-01
        • 2018-02-27
        • 2012-12-01
        相关资源
        最近更新 更多