简体   繁体   English

如何获取包含值列表的列名?

[英]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.

相关问题 熊猫:如何获取包含值列表的列的唯一值? - Pandas: how to get the unique values of a column that contains a list of values? 如何获取包含字典列表的数据框中列的每个值? - How to get each values of a column in a data frame that contains a list of dictionaries? 如果行包含列中列表中的两个值,如何过滤 dataframe - how to filter a dataframe if a rows contains two values from a list in a column 如何过滤列包含存储在列表中的值的 DataFrame? - How to Filter a DataFrame Where a Column Contains Values Stored in a List? 如何在整个Pandas数据帧中搜索字符串,并获取包含该字符串的列的名称? - How to search entire Pandas dataframe for a string and get the name of the column that contains it? 如何使用数据框中的值获取列名? - How to get the column name using values in a dataframe? 如果 Pyspark dataframe 的列包含 NaN 值,我该如何获取? - How can I get if a column of a Pyspark dataframe contains NaN values? 如何获取包含列表或值的列熊猫的唯一值? - how to get the unique value of a column pandas that contains list or value? 从SQL表获取值以及列名作为Python中的列表 - Get values from SQL table along with column name as list in Python 如何使用列名和列值从pandas DataFrame生成列表? - How to generate a list from a pandas DataFrame with the column name and column values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM