[英]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_D![]() |
Col_G ![]() |
---|---|---|---|
AA ![]() |
12 ![]() |
Q![]() |
no![]() |
BB ![]() |
23 ![]() |
W ![]() |
yes![]() |
WW![]() |
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.