PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

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

 May 13, 2022     append, dataframe, dictionary, pandas, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing