【问题标题】:Pandas (python): max in columns define new value in new column熊猫(python):列中的最大值在新列中定义新值
【发布时间】:2017-09-05 22:23:58
【问题描述】:

我有一个大约 50 列的 df:

Product ID | Cat1 | Cat2 |Cat3 | ... other columns ...
8937456       0      5     10
8497534       25     3     0
8754392       4      15    7 

Cat 表示该产品有多少数量属于某个类别。现在我想添加一个“类别”列,表示产品的主要类别(忽略其他列,只考虑 Cat 列)。

df_goal:

Product ID | Cat1 | Cat2 |Cat3 | Category | ... other columns ...
8937456       0      5     10       3
8497534       25     3     0        1
8754392       4      15    7        2

我想我需要使用 max 和 apply 还是 map?

我在 stackoverflow 上找到了这些,但它们没有解决类别分配问题。在 Excel 中,我将列从 Cat 1 重命名为 1 并使用 index(match(max))。

Python Pandas max value of selected columns

How should I take the max of 2 columns in a dataframe and make it another column?

Assign new value in DataFrame column based on group max

【问题讨论】:

    标签: python pandas numpy max apply


    【解决方案1】:

    这是numpy.argmax 的 NumPy 方式 -

    df['Category'] = df.values[:,1:].argmax(1)+1
    

    要将选择限制为这些列,请专门使用这些列标题/名称,然后使用idxmax,最后将字符串Cat替换为`空字符串,就像这样-

    df['Category'] = df[['Cat1','Cat2','Cat3']].idxmax(1).str.replace('Cat','')
    

    numpy.argmaxpanda's idxmax 基本上可以为我们获取沿轴的最大元素的 ID。

    如果我们知道Cat 列的列名从1st 列开始并以4th 结束,我们可以切片 数据框:df.iloc[:,1:4] 而不是@987654333 @。

    【讨论】:

    • 感谢您的快速回复;请问,argmax 是如何工作的?不幸的是,我在 df 中还有其他列;有没有办法将其限制为这些列,或者我应该将所需的列保存为自己的 df?
    • 选择那些列然后使用.values
    • 呃!杰出的!测试
    • df['Category'] = df[['Cat1','Cat2','Cat3']].idxmax(1).str.replace('Cat','') 完美运行;惊人的一个班轮;谢谢 - 希望我能给它不止一票
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2015-10-23
    • 2020-09-09
    • 2022-01-25
    • 1970-01-01
    • 2018-12-29
    • 2019-03-14
    相关资源
    最近更新 更多