Python 熊猫:比较列表值并写入新列

Python 熊猫:比较列表值并写入新列,python,pandas,Python,Pandas,我有一个新问题,关于我的工作。在那篇文章中,问题被简化了,只需要比较两个w。现在,假设我有超过2个,例如,3个,频率为(1,1,0)。我想检查这个列表,如果最大值出现了多次,写0,否则写最大值的列标签,如前一篇文章所示。我试图修改那篇文章的第一个答案,但我被卡住了 任何帮助都将不胜感激,谢谢您的关注。:-) 编辑: # You should drop all extra fields # don't worry they are still present in original datafra

我有一个新问题,关于我的工作。在那篇文章中,问题被简化了,只需要比较两个w。现在,假设我有超过2个,例如,3个,频率为(1,1,0)。我想检查这个列表,如果最大值出现了多次,写0,否则写最大值的列标签,如前一篇文章所示。我试图修改那篇文章的第一个答案,但我被卡住了

任何帮助都将不胜感激,谢谢您的关注。:-)

编辑:

# You should drop all extra fields
# don't worry they are still present in original dataframe (df)
words = df.drop(['FID'], axis=1)

# Get maximums for each row
maxes = words.max(axis=1)

# Create new column with the features names with maximum values
df['max'] = words.idxmax(axis=1)

# Create a mask with non-accepted rows
mask = (
    words.values.ravel() == maxes.values.repeat(len(words.columns)).ravel()
).reshape(-1,len(words.columns)).astype(int).sum(axis=1)>1

# Wipe 'max' column in non-accepted rows
df.ix[mask,'max'] = 0
我的真实df的一个例子是:


|FID |几何|网格代码|卡塔罗|康斯特帕多|格里帕|格里普|雷斯弗里奥|雷斯弗里奥
0  |9592|...     |9592    |1      |0         |0    |3    |     3   |  1

在这种情况下,所需输出为:

|FID |几何学|网格代码|卡塔罗|康斯特帕多|格里帕|格里普|雷斯弗里奥|雷斯弗里奥|马克斯
0  |9592|...     |9592    |1      |0         |0    |3    |     3   |  1    | 0

编辑:

# You should drop all extra fields
# don't worry they are still present in original dataframe (df)
words = df.drop(['FID'], axis=1)

# Get maximums for each row
maxes = words.max(axis=1)

# Create new column with the features names with maximum values
df['max'] = words.idxmax(axis=1)

# Create a mask with non-accepted rows
mask = (
    words.values.ravel() == maxes.values.repeat(len(words.columns)).ravel()
).reshape(-1,len(words.columns)).astype(int).sum(axis=1)>1

# Wipe 'max' column in non-accepted rows
df.ix[mask,'max'] = 0

这对我不起作用。当我将
df.filter(regex=r'w\d')
应用于我的df时,它返回一个空的df,只有index列。事实上我发现了我的问题,w是“单词”,它们不是w1,w2,w3。。。我将尝试修改这段代码。如果你告诉我更多关于你最初的任务,我相信我能帮你。例如,如果你正在使用单词频率,你可以使用机器学习中使用的一些变压器(,),我已经更新了我的第一篇帖子,抱歉耽搁了。我是新来的。那些是0-1列吗?是的,我想在最后6列中做一些事情