[英]How to query on a pandas data frame based on column values of specific row
[英]How to query Pandas df based on row values and column header with Python
有沒有辦法根據行值和列標題查詢 df? 希望通過Disney
、 World
和Value
作為變量返回55
。 我嘗試使用df.loc
函數但收到錯誤。 Key1
和Key2
標頭設置為df.index
。
熊貓數據框
鍵1 | 鍵2 | 價值 |
---|---|---|
迪士尼 | 世界 | 55 |
迪士尼 | 土地 | 97 |
如果 key1 和 key2 作為多索引在索引中,我認為你只需要這個。
df.loc[('Disney', 'World'), 'Value']
您可以使用此代碼獲取“值”的值
pd.read_csv(PATH)
data = data.dropna()
Value = data['Value'].values # Get values of 'Value'
# Key2 = data['Key2'].values # Get values of 'Key2'
print(Value)
輸出將是
[55, 97]
IIUC,您創建一個函數,傳遞參數並獲取返回值
df=df.set_index(['Key1', 'Key2'])
def findval(df, Key1, Key2):
return df.loc[(Key1, Key2), 'Value']
findval(df, 'Disney', 'Land')
結果:
97
或者
def findval(df, Key1, Key2):
return df[(df['Key1'] == Key1) &
(df['Key2'] == Key2)]['Value']
findval(df, 'Disney', 'Land')
1 97
名稱:值,數據類型:int64
只需直接在系列上發出多索引表達式:
df.Value['Disney', 'World']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.