简体   繁体   English

如何检查 dataframe pandas 中是否不存在列列表

[英]how to check if a list of column in not present in a dataframe pandas

I have a dataframe (df) and list (l) containing a list of column names.我有一个包含列名列表的 dataframe (df) 和列表 (l)。 df:东风:

Col_A可乐 Col_B Col_B Col_D寒冷的 Col_G Col_G
AA AA 12 12 Q no
BB BB 23 23 W W yes是的
WW万维网 44 44 yes是的
l = ['Col_A', 'Col_B', 'Col_C', 'Col_D', 'Col_E', 'Col_F', 'Col_G']

I would like to print the column names that are not present in the df.我想打印 df 中不存在的列名。

Desired output:所需的 output:

['Col_C', 'Col_E', 'Col_F']

What I tried so far:到目前为止我尝试了什么:

if l not in df.columns:
    print(l)

I get an error TypeError: unhashable type: 'list'我收到一个错误TypeError: unhashable type: 'list'

You can use list comprehension for this:您可以为此使用列表推导:

[i for i in l if i not in df.columns]

This goes through every element in l ( i ) and if it is not in the columns of df, it will add it to a new list.这会遍历l ( i ) 中的每个元素,如果它不在 df 的列中,它会将其添加到新列表中。 Output: Output:

['Col_C', 'Col_E', 'Col_F']

Use numpy.setdiff1d :使用numpy.setdiff1d

L = np.setdiff1d(l, df.columns).tolist()

Or Index.difference :Index.difference

L = pd.Index(l).difference(df.columns).tolist()

Or list comprehension with not in :或使用not in列出理解:

L = [x for x in l if x not in df.columns]

print (L)
['Col_C', 'Col_E', 'Col_F']

You have to loop over the list l .您必须遍历列表l

Like:喜欢:

for item in l:
  if item not in df.columns:
    print(item) 

You can use set difference:您可以使用设置差异:

list(set(l).difference(df.columns))

or或者

list(set(l) - set(df.columns))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pandas:如何检查数据框列中的任何列表是否存在于另一个数据帧的范围内? - Pandas: How to check if any of a list in a dataframe column is present in a range in another dataframe? 如何检查 pandas 列中的字符串列表的元素是否存在于另一列中 - How to check if elements of a list of strings in a pandas column are present in another column 检查pandas数据帧中的列值是否存在于系列中 - Check if a column value in a pandas dataframe is present in a series 如何检查Python中的列表中是否存在DataFrame字符串列的第一个单词? - How to check if first word of a DataFrame string column is present in a List in Python? 如何检查列表中的所有元素是否都存在于 pandas 列中 - How to check if all the elements in list are present in pandas column 对数据框熊猫的列中存在的列表执行计算 - Perform calculations on a list present in a column of a dataframe pandas Pandas Dataframe 检查列值是否在列列表中 - Pandas Dataframe Check if column value is in column list 如何检查一个pandas列中列表中的所有元素是否存在于另一个pandas列中 - How to check if all the elements in list in one pandas column are present in another pandas column 如何检查类型列表的熊猫数据框列值中存在的值 - how to check value existing in pandas dataframe column value of type list 熊猫:如何检查列表框是否在数据框中 - Pandas: How to check if a list-type column is in dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM