【问题标题】:Python - Pandas create column with np.where for multiple different valuesPython - Pandas 使用 np.where 为多个不同的值创建列
【发布时间】:2018-07-11 02:52:57
【问题描述】:

我有一个这样的数据框:

id year Q
1 2017 1
2 2017 2
3 2018 1
4 2018 2
5 2018 3

并且想要创建另一个名为 D 的列:

id year Q Desc
1 2017 1 '2017 first Quarter'
2 2017 2 '2017 second Quarter'
3 2018 1 '2018 first Quarter' 
4 2018 2 '2018 second Quarter' 
5 2018 3 '2017 third Quarter'

然而 np.where 似乎只接受 2 个参数(如果为真,如果为假)。所以想法是有一个可以处理多种可能性的 np.where 句子

【问题讨论】:

  • np.where的多选项版本是np.select

标签: python pandas numpy


【解决方案1】:

大致上,使用np.select

df['Desc'] = df.year.astype(str) + ' ' + np.select([df.Q==x for x in [1,2,3,4]], ['first', 'second', 'third', 'quarter']) + ' quarter'

【讨论】:

    【解决方案2】:

    IIUC 你只需要map你的Q列到character然后使用字符串总和

    df['Desc']=df.year.astype(str)+' '+ df.Q.map({1:'first',2:'second',3:'third',4:'fourth'})+' Quarter'
    df
    Out[26]: 
       id  year  Q                 Desc
    0   1  2017  1   2017 first Quarter
    1   2  2017  2  2017 second Quarter
    2   3  2018  1   2018 first Quarter
    3   4  2018  2  2018 second Quarter
    4   5  2018  3   2018 third Quarter
    

    【讨论】:

      【解决方案3】:

      使用+ & pandas.DataFrame.apply

      d={1:'first',2:'second',3:'third',4:'fourth'}
      df['Desc']=(df['year'].astype(str)+' '+df['Q'].astype(str)+' Quarter').apply(lambda x: ' '.join(d[int(i)] if len(i)==1 else i for i in x.split()))
      print(df)
      

      输出:

         id  year  Q                 Desc
      0   1  2017  1   2017 first Quarter
      1   2  2017  2  2017 second Quarter
      2   3  2018  1   2018 first Quarter
      3   4  2018  2  2018 second Quarter
      4   5  2018  3   2018 third Quarter
      

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 2016-08-04
        • 1970-01-01
        • 2017-07-27
        • 2017-11-08
        • 2021-06-23
        • 2020-12-04
        • 2018-07-16
        • 1970-01-01
        相关资源
        最近更新 更多