python - Pandas ( python ): max in columns define new value in new column

标签 python pandas numpy max apply

我有一个大约 50 列的 df:

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

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

df_目标:

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

我想我需要使用 max 并应用或映射?

我在 stackoverflow 上找到了这些,但它们并没有解决类别分配问题。在 Excel 中,我将列从 Cat 1 重命名为 1 并使用索引(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

最佳答案

这是使用 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 的 idxmax 基本上为我们提供了沿轴的最大元素的 ID。

如果我们知道 Cat 列的列名称从 1st 列开始,到 4th 列结束,我们可以切片数据帧:df.iloc[:,1:4]而不是df[['Cat1','Cat2','Cat3']] .

关于python - Pandas ( python ): max in columns define new value in new column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330555/

相关文章:

python - 如何连接两个数据框并在这样的特定列上对齐?

python - 查找特定字符串的行并读取该行之后的文本文件

python - 将 pandas 间隔数据框减少为 12 个月 x 24 小时聚合值的表

python - 在 Numpy 中将离散值的一维数组转换为连续值的 n 维数组

python - 当发送到 Pyramid/Cornice 应用程序时,Backbone.js HTTP PUT 请求失败并出现 404 错误

python - 如何在同一张图中绘制多个线性回归

python - 为什么在将ubuntu从12.04升级到14.04后使用python的numpy进行矩阵乘法变得如此缓慢?

python - 修改数组的值,其中相同大小的列表包含另一个列表的值

python - 在谷歌应用引擎中设计数据库

python - Stanza 抛出 "KeyError: ' feat_dropout'"