簡體   English   中英

通過將 pandas 數據框中的值作為字典鍵傳遞來訪問字典值

[英]access to a dictionary value by passing a value from a pandas dataframe as dictionary key

有一個 pandas df 和一本字典,它的鍵是從這個 df 中獲得的。 例如:

data = {'Type': [1, 1, 2, 3, 2] ,
    'Vol' : [10, 20, 15, 15, 15] ,
    'Cost' : [500, 300, 200, 250, 400] , 
    'IsSold' : [1, 1, 1, 1, 0]}

df = pd.DataFrame(data)

capacity = {key : 500 for key in df.Type.unique()}

一個 sub_dataframe 將創建只有一行數據:

sample_df = df.sample()

現在,我想這樣做:

if sample_df['Cost'] <= capacity[sample_df['Type']] :
   #some procedure

但是當我運行它時它返回一個錯誤:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

你能幫我嗎?

LHS 和 RHS 表達式都是 Pandas 系列——而不是“來自 pandas 數據框的值”。 一種可能的解決方案是獲取已采樣的 Series 的索引,並使用它來檢索值:

index = sample_df.index[0]
sample_df['Cost'][index] <= capacity[sample_df['Type'][index]]

該錯誤指出 Series 類型的對象不能用作字典的鍵,因為它是可變的。 Python 中的可變對象不能被散列,因此不能用作字典鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM