【发布时间】:2020-07-24 07:13:08
【问题描述】:
我想过滤一个数据框。生成的数据框应包含在任意列中包含列表中任何单词的所有行。
我开始使用 for 循环,但应该有更好的 pythonic/pandonic 方式。
例子:
# importing pandas
import pandas as pd
# Creating the dataframe with dict of lists
df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'],
'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'],
'Position': ['PG', 'PG', 'UG', 'PG', 'UG'],
'Number': [3, 4, 7, 11, 5],
'Age': [33, 25, 34, 35, 28],
'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'],
'Weight': [89, 79, 113, 78, 84],
'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'],
'Salary': [99999, 99994, 89999, 78889, 87779]},
index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5'])
df1 = df[df['Team'].str.contains("Boston") | df['College'].str.contains('MIT')]
print(df1)
因此很清楚如何单独过滤包含特定单词的列
进一步说明如何过滤包含列表中任何字符串的每列行:
df[df.Name.str.contains('|'.join(search_values ))]
其中 search_values 包含单词或字符串列表。
search_values = ['boston','mike','whatever']
我正在寻找一种简短的编码方式
#pseudocode
give me a subframe of df where any of the columns 'Name','Position','Team' contains any of the words in search_values
我知道我能做到
df[df['Name'].str.contains('|'.join(search_values )) | df['Position'].str.contains('|'.join(search_values )) | df['Team'].contains('|'.join(search_values )) ]
但如果我想要 20 列,那将是一堆乱七八糟的代码
有什么建议吗?
编辑奖励: 在查看列列表时,即“名称”、“职位”、“团队”如何包含索引?传递 ['index','Name','Position','Team'] 不起作用。
谢谢。
我看过这个: https://www.geeksforgeeks.org/get-all-rows-in-a-pandas-dataframe-containing-given-substring/
https://kanoki.org/2019/03/27/pandas-select-rows-by-condition-and-string-operations/
【问题讨论】: