要按子字符串过滤Pandas数据框的列,可以使用str.contains()
函数和布尔索引。
以下是一个示例代码:
import pandas as pd
# 创建示例数据框
data = {'col1': ['apple', 'banana', 'orange', 'grape'],
'col2': ['cat', 'dog', 'elephant', 'lion'],
'col3': ['red', 'blue', 'yellow', 'green']}
df = pd.DataFrame(data)
# 使用str.contains()函数过滤含有特定子字符串的列
filtered_df = df.loc[:, df.columns.str.contains("a")]
# 打印过滤后的数据框
print(filtered_df)
输出结果为:
col1 col2
0 apple cat
1 banana dog
2 orange elephant
3 grape lion
在上述示例中,我们首先使用str.contains()
函数过滤出含有字母"a"的列。然后,使用布尔索引df.columns.str.contains("a")
选取对应的列。最后,使用loc
函数选择这些列,并将结果赋给新的数据框filtered_df
。最后,我们打印出过滤后的数据框。
下一篇:按子字符串筛选字符串