1

So I have a DataFrame that looks like the following

   a   b   c  
0  AB  10  {a: 2, b: 1}
1  AB  1   {a: 3, b: 2}
2  AC  2   {a: 4, b: 3}
...   
400 BC 4   {a: 1, b: 4}

Given another key pair like {c: 2} what's the syntax to add this to every value in row c?

   a   b   c  
0  AB  10  {a: 2, b: 1, c: 2}
1  AB  1   {a: 3, b: 2, c: 2}
2  AC  2   {a: 4, b: 3, c: 2}
...   
400 BC 4   {a: 1, b: 4, c: 2}

I've tried df['C'] +=, and df['C'].append(), and df.C.append, but neither seem to work.

SharpObject
  • 597
  • 5
  • 17

1 Answers1

2

Here is a generalized way for updating dictionaries in a column with another dictionary, which can be used for multiple keys.

Test dataframe:

>>> x = pd.Series([{'a':2,'b':1}])
>>> df = pd.DataFrame(x, columns=['c'])
>>> df
                  c
0  {'b': 1, 'a': 2}

And just apply a lambda function:

>>> update_dict = {'c': 2}
>>> df['c'].apply(lambda x: {**x, **update_dict})
0    {'b': 1, 'a': 2, 'c': 2}
Name: c, dtype: object

Note: this uses the Python3 update dictionary syntax mentioned in an answer to How to merge two Python dictionaries in a single expression?. For Python2, you can use the merge_two_dicts function in the top answer. You can use the function definition from that answer and then write:

df['c'].apply(lambda x: merge_two_dicts(x, update_dict))
Community
  • 1
  • 1
brianpck
  • 8,084
  • 1
  • 22
  • 33