如何选择数据框的所有列,这些列部分匹配列表中的字符串?

问题描述 投票:0回答:1

假设我有一个像这样的数据框:

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]}
.

python pandas string-matching
1个回答
1
投票

您可以使用

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)
© www.soinside.com 2019 - 2024. All rights reserved.