一整天都在寻找解决我问题的方法,却找不到答案。我试着按照这个主题的例子:Get column name where value is something in pandas dataframe 生成具有多个条件的版本
我想提取列名(在列表下)其中:
值==4或/和值==3
+
仅当没有4或/和3时,才提取value==2的列名
例如:
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'acne': [1, 4, 1, 2], 'wrinkles': [1, 3, 4, 4],'darkspot': [2, 2, 3, 4] }
df1 = pd.DataFrame(data)
df1
df1
'''
Name acne wrinkles darkspot
0 Tom 1 1 2
1 Joseph 4 3 2
2 Krish 1 4 3
3 John 2 4 4
'''
我正在寻找的结果:
df2
Name acne wrinkles darkspot problem
0 Tom 1 1 2 [darkspot]
1 Joseph 4 3 2 [acne, wrinkles]
2 Krish 1 4 3 [wrinkles, darkspot]
3 John 2 4 4 [wrinkles, darkspot]
'''
我在上面提到的主题中使用了带有lambda的apply函数,但它只能接受一个参数。 如果有人能帮助我,非常感谢您的回答:)
您可以使用布尔掩码来确定需要哪些列
首先检查值是否为3或4,如果不是,则检查值是否为2。在这两个条件之间使用
|
(or)形成复合掩码(下面的变量m
)最后,您可以
NaN
假值,这样当您进行堆栈时,groupby.agg(list)
只剩下真值的列标签您可以使用布尔掩码:
输出:
相关问题 更多 >
编程相关推荐