[英]How to get the column name that contains a list of values?
I am trying to return the column name that has the strings from a list.我正在尝试从列表中返回包含字符串的列名。
import pandas as pd
names = ['Brian', 'John']
df = pd.DataFrame(columns=["A", "B", "C", "D", "E", "F"], data=[['abc']*6]*6)
df['D'] = ['Brian', 'John', "Mike", 'Brian', 'John', "Mike"]
print(df)
col_name = ([i for i in df if df [i].isin([names]).any()])
This does not work with a list.这不适用于列表。 Is there any way to pass this the list of names and print the column name that contains those values?
有什么方法可以传递名称列表并打印包含这些值的列名?
Try with:尝试:
df.columns[df.isin(names).any()]
Output: Output:
Index(['D'], dtype='object')
Your solution should be modified to:您的解决方案应修改为:
df.columns[[df[i].isin(names).any() for i in df]]
Or you can try with:或者您可以尝试:
df.columns[df.stack().isin(names).any(level=1)]
Index(['D'], dtype='object')
If you are trying to get the columns that contain both names (and not just one), this should work:如果您试图获取包含两个名称(而不仅仅是一个)的列,这应该有效:
df.loc[:,df.stack().loc[lambda x: x.isin(names)].groupby(level=1).agg(set).eq(set(names))].columns
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.