我有一個 Excelfile,我用 pandas 將其讀入資料框。在這個 Excelfile 中有不同的鍵值對。
我想搜索鍵并獲取值(帶有行和/或列偏移)
到目前為止,這是我的代碼(帶有示例資料框):
import json
import pandas as pd
def SearchValues(df,str_search,r_offset,c_offset):
print(df[df.eq(str_search).any(1)])
#return Value
data = {'Unnamed: 1': ['', ''],
'Unnamed: 2': ['', 'Key1'],
'Unnamed: 3': ['', ''],
'Unnamed: 4': ['', 'Value1'],
'Unnamed: n': ['Key2', 'Value2'],
}
df = pd.DataFrame(data)
SearchValues(df,'Key1',0,2) #=> result= Value1
SearchValues(df,'Key2',1,0) #=> result= Value2
我在搜索功能中掙扎。這是一種可能的方式嗎?如果是,我該如何進行?或者有沒有其他選擇。也許沒有資料框直接在 Excelfile 中搜索。
uj5u.com熱心網友回復:
您可以將索引重置為具有數字范圍,然后使用堆疊的 DataFrame 來識別第一個匹配項并獲取索引,然后在添加偏移量后進行切片:
def SearchValues(df, str_search, r_offset, c_offset):
# reset the index/columns to be a numerical range
df = df.set_axis(range(df.shape[1]), axis=1).reset_index(drop=True)
# find the row/col coordinates of the first match
r,c = df.eq(str_search).stack().idxmax()
# add the offsets and slice based on position
return df.loc[r r_offset, c c_offset]
SearchValues(df, 'Key1', 0, 2)
# 'Value1'
SearchValues(df, 'Key2', 1, 0)
# 'Value2'
注意。這不能處理偏移量使其溢位 DataFrame 尺寸的情況,但是很容易添加檢查使用df.shape
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486404.html
下一篇:反應地圖-回傳值
