0

I have some DataFrames:

d = {'colA': [1, 2], 'colB': [3, 4]}

df = pd.DataFrame(data=d)
df2 = pd.DataFrame(data=d)
df3 = pd.DataFrame(data=d)

I want to return a list of columns containing the string 'A', e.g. for one DataFrame:

[column for column in df.columns if 'A' in column]

How can I do this for multiple DataFrames (e.g., df, df2, df3)?

The desired output in this example would be ['colA', 'colA', 'colA']

2 Answers 2

1

Here is a way:

l = [','.join(i.columns[i.columns.str.contains('A')]) for i in [df,df2,df3]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a function for that:

def find_char(list_of_df , char):
    result = []
    for df in list_of_df:
        for c in df.columns:
            if char in c:
                result.append(c)
    return result

Usage:

res = find_char([df,df2,df3] , 'A')
print(res)
['colA', 'colA', 'colA']

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.