2017-11-16 2 views
0

사전에 사전을 사용하고 있습니다. pandas 데이터 프레임을 반복하면서 액션 행의 값은 사전의 키 중 하나와 항상 일치하며 그 행의 다른 값이 해당 사전의 목록에 추가됩니다. 어떤 이유로, 그러나, 다른 값이 사전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 함수입니다 (예 : 클래스) :

import copy 
for action in action_types: 
    sheetstats[action] = copy.deepcopy(general_form)