1

I have the following dataframes in python

dataframe_list= []## CREATE AN EMPTY LIST
import pandas as pd

A=pd.DataFrame()
A["name"]=["A", "A", "A"]
A["Query"]=["B", "B", "B"]


B=pd.DataFrame()
B["name"]=["A", "A", "A"]
B["Col"]=["query", "B", "B"]

C=pd.DataFrame()
C["name"]=["A", "A", "A"]
C["Col"]=["C", "B", "B"]

 dataframe_list.append(A)
 dataframe_list.append(B)
 dataframe_list.append(C)

The list of dataframes contain 3 dataframes in this toy example. I would like to obtain a list of dataframes containing the word query either as a column name or as a table entry. IHow do I accomplish this. I tried the following loop

dataframe_list2=[]

for i in dataframe_list:
      
for column in i:
    try:
            m1=i[column].str.contains('query').sum()
            column = column.lower()
            m2 = column.count("query")
            mel_count = m1+m2
    except:
        pass
    
    dataframe_list2.append(i)  

This however results in a a list with duplicate entries. I want each table to be mentioned just once. Is there a simple elegant solution for this.

3
  • 1
    if the only problem is duplicate entries, why not use set(list)
    – Yash
    Sep 21, 2020 at 12:11
  • Not sure what you want to do. Do you want to filter dataframes that have string "query" either in their column names or in an individual cell?
    – Chris
    Sep 21, 2020 at 12:16
  • Yes I want to filter the columns containing string Query Sep 22, 2020 at 3:32

1 Answer 1

1

Use list comprehension with test each column in DataFrame.apply if contain query or test if column name contains too and filter by if:

dataframe_list2 = [x for x 
                   in dataframe_list 
                   if x.apply(lambda x: x.str.contains('query')).any().any() or 
                   any(x.columns.str.lower() == 'query')]
print (dataframe_list2)
[  name Query
0    A     B
1    A     B
2    A     B,   name    Col
0    A  query
1    A      B
2    A      B]

Loop alternative is:

dataframe_list2=[]

for x in dataframe_list:
    m1 = x.apply(lambda x: x.str.contains('query')).any().any()
    m2 = any(x.columns.str.lower() == 'query')
    if m1 or m2:
        dataframe_list2.append(x)

print (dataframe_list2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.