【问题标题】:Getting list of column headers based on condition per row in Pandas DF根据 Pandas DF 中每行的条件获取列标题列表
【发布时间】:2020-10-27 03:08:57
【问题描述】:

我想知道是否可以根据条件获取列标题列表。例如,如果我的条件是获取每个单元格中具有“MATCH”值的列标题列表,它将输出列表列表或包含标题名称的字符串列表,如下所示:

["a, c", "b, d", "a, b, c, d", "a, d"]
or 
[["a", "c"], ["b", "d"], ["a", "b", "c", "d"], ["a", "d"]]

感谢您的帮助!

【问题讨论】:

  • 看起来你想迭代每一行?为什么第一个元素是"a", "c",而第一行的d 中有match

标签: python pandas list loops


【解决方案1】:

你可以试试np.where:

import pandas as pd
import numpy as np
df=pd.DataFrame({'a': ['match','mismatch','match'],'b': ['match','match','mismatch'],'c': ['mismatch','mismatch','match']})

print(df)

arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)

print(arr)

输出:

df
          a         b         c
0     match     match  mismatch
1  mismatch     match  mismatch
2     match  mismatch     match

arr
['ab' 'b' 'ac']

然后,要获得所需的列表,您可以尝试:

#first option
arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)
arr=list(map(', '.join,arr))
print(arr)

#second option
arr= np.where(df.eq('match'), df.columns, '').sum(axis=1)
arr=list(map(list,arr))
print(arr)

输出:

#first option
['a, b', 'b', 'a, c']

#second option
[['a', 'b'], ['b'], ['a', 'c']]

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2020-11-30
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多