简体   繁体   中英

creating list from dataframe where column name contains particular string

I referred to the solution here - Find column whose name contains a specific string

spike_cols = [col for col in df.columns if 'spike' in col]

However, I want to search for multiple strings at once. For example, I tried to search for string 'keyword' by implementing -

spike_cols = [col for col in df.columns if 'spike | keyword' in col]

This doesn't return the list I desire. Any pointers on how to proceed ?

Also possible:

# create list for words
words = ['spike', 'keyword']

# store col names in list
cols = list(df.columns)

# list comprehension to return idxs for matches
idx_matches = [i for i in range(len(cols)) if cols[i] in words]

# access the df cols
df.iloc[:, idx_matches]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM