2017-11-16 2 views
0

辞書の中で言い訳を使用しています。 pandasデータフレームをループすると、アクション行の値は常に辞書のキーの1つと一致し、その行の他の値がその辞書のリストに追加されます。何らかの理由で、しかし、値が他の辞書pythonがすべての辞書に追加されます

general_form = { 
     "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": [] 
    } 
    #get all possible action types 
    action_types = self.df['Action Type'].tolist() 
    action_types = list(set(action_types)) 

    #give every action type its own dictionary within the main dictionary 
    sheetstats = {} 
    for action in action_types: 
     sheetstats[action] = general_form 

    #push the percentage in the list inside the dictionary specified in 
    #action 
    for index, row in self.df.iterrows(): 
     percentage = row['Percentage'] 
     daypercentage = row['DayPercentage'] 
     action = row['Action Type'] 
     sheetstats[action]['Percentages'].append(percentage) 
     sheetstats[action]["DayPercentages"].append(daypercentage) 

これはsheetstats内のすべての辞書で同じ割合のすべてを行います内のすべてのリストに追加されます。どうして?

+0

*同じ辞書*: 'sheetstats [action] = general_form'を使用しているためです。 –

+1

'sheetstats [action] = general_form'は、すべてのキースロットに同じ辞書を入れたいと言っています...あなたは' general_form'をコピーしたいと思います – MooingRawr

答えて

0

すべての反復でgeneral_formを割り当てています。

action_typesの値を割り当てることはできますか?

sheetstats [action] = action_types [action]?

general_form = { 
     "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": [] 
    } 
    #get all possible action types 
    action_types = self.df['Action Type'].tolist() 
    action_types = list(set(action_types)) 

    #give every action type its own dictionary within the main dictionary 
    sheetstats = {} 
    for action in action_types: 
     sheetstats[action] = action_types[action] 

    #push the percentage in the list inside the dictionary specified in 
    #action 
    for index, row in self.df.iterrows(): 
     percentage = row['Percentage'] 
     daypercentage = row['DayPercentage'] 
     action = row['Action Type'] 
     sheetstats[action]['Percentages'].append(percentage) 
     sheetstats[action]["DayPercentages"].append(daypercentage) 
2
sheetstats[action] = general_form 

基本的にすべてのキースロットに同じ辞書を入れているあなたは何ができるか、バックgeneral_form

に向いて各キーがgeneral_formのコピーを作成しているとして、あなたはこの考えることができます。

for action in action_types: 
    sheetstats[action] = dict(general_form) 

データ構造をコピーする適切な方法は、copyモジュールを使用し、それはdeepcopyディープstrをコピーする関数です

import copy 
for action in action_types: 
    sheetstats[action] = copy.deepcopy(general_form) 
関連する問題