Ber*_*nes 5 python filter pandas
我想过滤一个数据框。生成的数据帧应包含所有行,其中任意多个列中包含列表中的任何单词。
我开始使用 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)
Run Code Online (Sandbox Code Playgroud)
因此很清楚如何单独过滤包含特定单词的列
此外,还清楚如何过滤包含列表中任何字符串的每列行:
df[df.Name.str.contains('|'.join(search_values ))]
Run Code Online (Sandbox Code Playgroud)
其中 search_values 包含单词或字符串的列表。
search_values = ['boston','mike','whatever']
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种简短的编码方法
#pseudocode
give me a subframe of df where any of the columns 'Name','Position','Team' contains any of the words in search_values
Run Code Online (Sandbox Code Playgroud)
我知道我能做到
df[df['Name'].str.contains('|'.join(search_values )) | df['Position'].str.contains('|'.join(search_values )) | df['Team'].contains('|'.join(search_values )) ]
Run Code Online (Sandbox Code Playgroud)
但如果我有 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/
您还可以stack使用anyon 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)]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7917 次 |
| 最近记录: |