[英]Python pandas selecting subset of dataframe using filter condition
I have a Pandas DataFrame as below我有一个 Pandas DataFrame 如下
enter image description here I want to query on the columns to find out all the columns that contain 'X' for each Name. enter image description here我想查询列以找出每个名称包含“X”的所有列。
sample output be like: (John, O, P) here O and P are the column ids against John that have the character 'X'.示例 output 类似于:(John, O, P) 这里 O 和 P 是针对 John 的具有字符“X”的列 ID。 I tried query on Dataframe on columns using loc, but didn't get the output. please guide to get the required output.
我尝试使用 loc 在列上查询 Dataframe,但没有得到 output。请指导以获取所需的 output。
Here is a proposition using pandas.DataFrame.apply
and dict
to return a dictionnary where the keys are the person names and the values are the columns names that fulfill the condition (is equal to "X"
)这是一个使用
pandas.DataFrame.apply
和dict
返回字典的命题,其中键是人名,值是满足条件的列名(等于"X"
)
dico= dict(zip(df["Name"], df.eq("X").apply(lambda x: x.index[x].tolist(), axis=1)))
print(dico)
{'John': ['O', 'P'], 'Dave': ['M', 'P']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.