【问题标题】:Create Categorical Variable based on Maximum of Three Columns [duplicate]根据最多三列创建分类变量[重复]
【发布时间】:2019-08-12 10:06:53
【问题描述】:

我有一个数据框,其中包含某些新闻文章的情绪概率,如下所示:

sentimentPositive sentimentNegative sentimentNeutral 0.219640 0.010708 0.769652 0.539188 0.088198 0.372615 0.561837 0.264411 0.173752 0.570648 0.255499 0.173853 0.525263 0.097155 0.377582

我现在想创建一个新的分类列,告诉我行中的哪种情绪具有最高概率,并使用例如(0, 1, 2) 为主导情绪。

最终输出应如下所示:

sentimentPositive sentimentNegative sentimentNeutral Sentiment 0.219640 0.010708 0.769652 2 0.539188 0.088198 0.372615 0 0.561837 0.264411 0.173752 0 0.570648 0.255499 0.173853 0 0.097155 0.525263 0.377582 1

我知道我可以通过以下方式获取列的最大值:

df["max"] = df[["sentimentPositive","sentimentNegative","sentimentNeutral"]].max(axis=1)

然后可以将max 列中的值与其他值进行比较以检查类别。但应该有一种更疯狂的方式来做到这一点,对吧?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    使用numpy.argmax 表示职位:

    cols = ["sentimentPositive","sentimentNegative","sentimentNeutral"]
    df["max"] = df[cols].values.argmax(axis=1)
    #for columns names
    #df["max"] = df[cols].idxmax(axis=1)
    print (df)
       sentimentPositive  sentimentNegative  sentimentNeutral  max
    0           0.219640           0.010708          0.769652    2
    1           0.539188           0.088198          0.372615    0
    2           0.561837           0.264411          0.173752    0
    3           0.570648           0.255499          0.173853    0
    4           0.097155           0.525263          0.377582    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2017-05-31
      • 2020-07-18
      • 2019-03-01
      • 2016-09-15
      • 1970-01-01
      相关资源
      最近更新 更多