0

My DataFrame looks something like this:

A,  B
1,  f

I've got a dictionary which looks like this:

{'M':[1,2,3]}

What i'd like to do is to add the dict into the Dataframe as a column:

A,  B,  C
1,  f,  {'M':[1,2,3]}

It's not important for the C column to be a dict i just need a key value pair where the value is an array.

Could someone explain to men how i could do this?

5
  • 2
    df.loc[0, 'C'] = {'M' : [1, 2, 3]} Commented Apr 11, 2018 at 13:53
  • @cᴏʟᴅsᴘᴇᴇᴅ - Working nice Commented Apr 11, 2018 at 13:55
  • 1
    @jezrael thanks man... was wondering whether it was a dupe, but could not find one so am posting an answer ... Commented Apr 11, 2018 at 13:56
  • 1
    Why, but why, would you do this?? Commented Apr 11, 2018 at 13:56
  • @colspeed thanks but i had the problem that i had multiple keys and then an error occured the solution was to put the dict into an array and then it worked. At least i do understand it better now Thank you! Commented Apr 11, 2018 at 14:19

3 Answers 3

4

With assign

df.assign(C=[{'M': [1, 2, 3]}])

   A  B                 C
0  1  f  {'M': [1, 2, 3]}
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh thank you very much. My fault was to add the dict directly so i had a value error. The dict must be inside of an array.
@swas if you were trying to add more than one dict, you should have indicated as such in your question
3

Assign with loc:

df.loc[0, 'C'] = {'M' : [1, 2, 3]}

df
   A  B                 C
0  1  f  {'M': [1, 2, 3]}

Comments

2

Adding []

df['C']=[{'M':[1,2,3]}]
df
Out[11]: 
   A    B                 C
0  1    f  {'M': [1, 2, 3]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.