Friday, May 13, 2022

[FIXED] When appending to a list within a dictionary within a Pandas DataFrame, it appends to all dictionaries in column instead of the one I'm pointing to

Issue

This is my code

import pandas as pd

keys = ['phone match', 'account match']
d = {k: [] for k in keys}

df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C'])
df['D'] = [d for _ in range(df.shape[0])]
df.at[0, 'D']['phone match'].append(4)

But instead of appending only on the dictionary at index 0 it appends to all the dictionaries and therefore the output is:

   A  B  C                                          D
0  1  2  3  {'phone match': [4], 'account match': []}
1  4  5  6  {'phone match': [4], 'account match': []}

While the desired output is:

   A  B  C                                          D
0  1  2  3  {'phone match': [4], 'account match': []}
1  4  5  6  {'phone match': [], 'account match': []}

I think this is because python is linking to the same dictionary, but how can I avoid that?


Solution

You need to create multiple dict in order to make each of them have different object ID

keys = ['phone match', 'account match']
df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C'])
df['D'] = [{k: [] for k in keys} for _ in range(df.shape[0])] # Change here 
df.at[0, 'D']['phone match'].append(4)
df
Out[65]: 
   A  B  C                                          D
0  1  2  3  {'phone match': [4], 'account match': []}
1  4  5  6   {'phone match': [], 'account match': []}


Answered By - BENY
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.