我需要帮助在 pandas Dataframe 上搜索值列表,然后分隔找到值的行

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

我希望实现什么: 我想知道在 pandas Dataframe 中查找列表的任何值,然后分隔找到该值的行的最佳方法是什么。

这是我尝试过的

def searchXlsx(xlsx_file: str, numbers: list) -> list:
    
    with open(os.path.realpath(xlsx_file), "rb") as i:
        i = pd.read_excel(i)
        print(i[i.isin(numbers)])

我想返回它所在的行

python pandas dataframe xlsx
1个回答
0
投票

您可以使用

.isin

import numpy as np
import pandas as pd

searchvals = np.array([1,45,87,9]) #The values to find

size = (100000, 10)
columns = [f"col_{x}" for x in range(size[1])]
df = pd.DataFrame(data=np.random.randint(low=0, high=1000, size=size), columns=columns)

matches = df.isin(searchvals).any(axis=1)

df2 = df.loc[matches]
df2.head()
#       col_0  col_1  col_2  col_3  col_4  col_5  col_6  col_7  col_8  col_9
# 34       793    893    435    312    812     87    990    552    496    397
# 47       818    902    478    479    736     83    135     45    180    224
# 55         9    750    118    910    205    866    617    232    506    755
# 94       326    303    868      9    583    310    668    614    720     50
# 99       167    148    586    570    196    473    829     87    266    194
© www.soinside.com 2019 - 2024. All rights reserved.