我想要过滤一个数据。结果的dataframe应该包含所有行,在任何一个列中都包含列表中的任何单词。
我开始使用循环,但应该有一个更好的丙酮/熊猫的方式。
示例:
# 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列的话,那将是一整行代码
有什么建议吗?
编辑奖励:查看列列表时,即“名称”、“职位”、“团队”传递“索引”、“名称”、“位置”、“团队”不起作用。
谢谢。
我看过这个: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/
发布于 2020-04-11 15:12:44
您还可以在stack
上使用any
进行level=0
cols_list = ['Name','Team'] #add column names
df[df[cols_list].stack().str.contains('|'.join(search_values),case=False,na=False)
.any(level=0)]
Name Team Position Number Age Height Weight College Salary
ind1 Geeks Boston PG 3 33 6-2 89 MIT 99999
ind2 Peter Boston PG 4 25 6-4 79 MIT 99994
ind3 James Boston UG 7 34 5-9 113 MIT 89999
发布于 2020-04-11 15:07:56
用apply
做any
df[[c1,c2..]].apply(lambda x : x.str.contains('|'.join(search_values )),axis=1).any(axis=1)
发布于 2020-04-11 15:09:21
在这种情况下,您可以简单地使用apply
:
cols_to_filter = ['Name', 'Position', 'Team']
search_values = ['word1', 'word2']
patt = '|'.join(search_values)
mask = df[cols_to_filter].apply(lambda x: x.str.contains(patt)).any(1)
df[mask]
https://stackoverflow.com/questions/61158898
复制相似问题