假设我有一个像这样的数据框:
import pandas as pd
df = pd.DataFrame({'foo': [1, 2, 3], 'bar': [4, 5, 6], 'ber': [7, 8, 9]})
给定一个像
mylist = ['oo', 'ba']
这样的“过滤器”字符串列表,我如何选择 df
中名称与 mylist
中的任何字符串部分匹配的所有列?对于这个例子,预期输出是{'foo': [1, 2, 3], 'bar': [4, 5, 6]}
.
您可以使用
df.filter
和 regex
来做到这一点。
import pandas as pd
# sample dataframe
df = pd.DataFrame({'foo': [1, 2, 3], 'bar': [4, 5, 6], 'ber': [7, 8, 9]})
# sample list of strings
mylist = ['oo', 'ba']
# join the list to a single string
matches = '|'.join(mylist)
# use regex to filter the columns based on the string
df_out = df.filter(regex=matches)