2017-05-21 33 views
1

這聽起來與很多SO問題類似,但我沒有真正找到它;如果它在這裏,請隨時鏈接,我會刪除。使用基於數據框中其他列的函數向pandas數據框添加值

我有兩個數據框。第一個看起來像這樣:

owned category       weight mechanics_split 
28156 Environmental, Medical    2.8023 [Action Point Allowance System, Co-operative P... 
9269 Card Game, Civilization, Economic 4.3073 [Action Point Allowance System, Auction/Biddin... 
36707 Modern Warfare, Political, Wargame 3.5293 [Area Control/Area Influence, Campaign/Bat... 

第二個看起來像這樣:

type       amount owned 
0 Action Point Allowance System 378  0 
1 Co-operative Play    302  0 
2 Hand Management     1308 0 
3 Point to Point Movement   278  0 
4 Set Collection     708  0 
5 Trading       142  0 

我試圖做的是遍歷每個單詞mechanics_split以便在第一數據幀的owned值添加到第二個數據幀中的owned列。例如,如果骰子滾動位於mechanics_split列的第一行games中,則整個數據框中該整行的擁有量將被添加到games_owned['owned'],依此類推,對於mechanics_split列表中的每個值。

到目前爲止,我已經試過:

owned_dict = {} 
def total_owned(x): 
    for e in x: 
     if e not in owned_dict: 
      owned_dict[e] = 0 
     if e in owned_dict: 
      owned_dict[e] += games['owned'][x] 
    return owned_dict 

其返回:

KeyError: "None of [['Action Point Allowance System', 'Co-operative Play', 'Hand Management', 'Point to Point Movement', 'Set Collection', 'Trading', 'Variable Player Powers']] are in the [index]" 

如果我e前添加另一封信中,有人告訴我有太多值解壓。我也嘗試跳過字典,只使用otherdf['owned'][e] += games['owned'][x]無濟於事。

我可能從根本上誤解了一些關於索引如何在熊貓中工作以及如何將值索引到一行的問題,所以如果是,請告訴我。非常感謝您的幫助。

編輯:我解決了部分問題,通過更改第二個數據框的索引到'otherdf.index = otherdf.types'的'類型'列,但我仍然留下了傳輸問題第一個數據幀擁有的值。

+0

請不要將數據發佈爲圖片。這迫使任何想要幫助的人重新輸入整個數據集。猜猜看,很多人不會打擾。 –

+0

固定,謝謝你的提示 – snapcrack

回答

1

我同意你使用'type'列作爲基於標籤的索引會使事情變得更容易。完成此操作後,您可以遍歷第一個數據幀的行,然後使用。將所有值添加到第二個數據幀中的相應行。 loc method

for row_1 in df_1.itterrows(): 
    owned_value = row_1[1]['owned'] #iterrows() enumeration generator over rows  
    mechanics = row_1[1]['mechanics_split'] 
    for type_string in mechanics: 
    df_2.loc[type_string,('owned')] += owned_value 

另外,我建議您閱讀how Pandas handles indexing,以幫助避免任何「陷阱」當你繼續使用Python工作。

+0

我很難複製你的代碼,並不知道爲什麼它不起作用。效果很好,非常感謝答案和對類似索引的建議 – snapcrack

+0

有關這個問題的一個問題,如果你還在附近:在這種情況下''[1]'是指什麼?它拋出了一點點 – snapcrack

+1

@snapcrack .iterrows()返回一個生成器,它在數據幀行上生成一個枚舉的連續元素。 python枚舉的形式是一個元組(integer_index,object),其中'object'是迭代的序列靜態的元素。因此,如果我們想要實際的數據幀行,它將存儲在此元組的第二個位置,而不是第一個位置。 – Bey

相關問題