簡體   English   中英

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

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

我有一個包含列名列表的 dataframe (df) 和列表 (l)。 東風:

可樂 Col_B 寒冷的 Col_G
AA 12
BB 23 W 是的
萬維網 44 是的
l = ['Col_A', 'Col_B', 'Col_C', 'Col_D', 'Col_E', 'Col_F', 'Col_G']

我想打印 df 中不存在的列名。

所需的 output:

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

到目前為止我嘗試了什么:

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

我收到一個錯誤TypeError: unhashable type: 'list'

您可以為此使用列表推導:

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

這會遍歷l ( i ) 中的每個元素,如果它不在 df 的列中,它會將其添加到新列表中。 Output:

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

使用numpy.setdiff1d

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

Index.difference

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

或使用not in列出理解:

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

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

您必須遍歷列表l

喜歡:

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

您可以使用設置差異:

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

或者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM