【问题标题】:create categorical variables by condition in python with pandas or statsmodels使用 pandas 或 statsmodels 在 python 中按条件创建分类变量
【发布时间】:2016-04-24 08:52:04
【问题描述】:

我想用这种方法从我的数据中创建分类变量:

cat.var  condition
1          x > 10
2          x == 10
3          x < 10

我尝试使用 patsy 中的 C() method ,但它不起作用,我知道在 stata 中我必须使用下面的代码,但搜索后我在 pyhton 中没有找到任何干净的方法来执行此操作:

generate mpg3    = .   

 (74 missing values generated) 

replace  mpg3    = 1 if (mpg <= 18) 

 (27 real changes made) 

replace  mpg3    = 2 if (mpg >= 19) & (mpg <=23) 

 (24 real changes made) 

replace  mpg3    = 3 if (mpg >= 24) & (mpg <.) 

 (23 real changes made

【问题讨论】:

    标签: python pandas statsmodels patsy


    【解决方案1】:

    您可以这样做(我们将只为列:a 这样做):

    In [36]: df
    Out[36]:
         a   b   c
    0   10  12   6
    1   12   8   8
    2   10   5   8
    3   14   7   7
    4    7  12  11
    5   14  11   8
    6    7   7  14
    7   11   9  11
    8    5  14   9
    9    9  12   9
    10   7   8   8
    11  13   9   8
    12  13  14   6
    13   9   7  13
    14  12   7   5
    15   6   9   8
    16   6  12  12
    17   7  12  13
    18   7   7   6
    19   8  13   9
    
    df.a[df.a < 10] = 3
    df.a[df.a == 10] = 2
    df.a[df.a > 10] = 1
    
    In [40]: df
    Out[40]:
        a   b   c
    0   2  12   6
    1   1   8   8
    2   2   5   8
    3   1   7   7
    4   3  12  11
    5   1  11   8
    6   3   7  14
    7   1   9  11
    8   3  14   9
    9   3  12   9
    10  3   8   8
    11  1   9   8
    12  1  14   6
    13  3   7  13
    14  1   7   5
    15  3   9   8
    16  3  12  12
    17  3  12  13
    18  3   7   6
    19  3  13   9
    
    In [41]: df.a = df.a.astype('category')
    
    In [42]: df.dtypes
    Out[42]:
    a    category
    b       int32
    c       int32
    dtype: object
    

    【讨论】:

      【解决方案2】:

      我正在使用这个 df 作为示例。

      >>> df
           A
      0    3
      1   13
      2   10
      3   31
      

      你可以像这样使用.ix

      df['CAT'] = [np.nan for i in range(len(df.index))]
      df.ix[df.A > 10, 'CAT'] = 1
      df.ix[df.A == 10, 'CAT'] = 2
      df.ix[df.A < 10, 'CAT'] = 3
      

      或者定义一个函数来完成这项工作,像这样:

      def do_the_job(x):
          ret = 3
          if (x > 10):
              ret = 1
          elif (x == 10):
              ret = 2
      
          return ret
      

      最后在你的 df 中正确的系列上运行它,像这样:

      >> df['CAT'] = df.A.apply(do_the_job)
      >> df
           A   CAT
      0    3     3
      1   13     1
      2   10     2
      3   31     1
      

      希望对你有所帮助!

      【讨论】:

        猜你喜欢
        • 2019-09-08
        • 1970-01-01
        • 2019-11-22
        • 2018-10-13
        • 2016-11-13
        • 2018-06-19
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        相关资源
        最近更新 更多