Best way to add dictionary to dataframe

I have a Pandas Dataframe and I want to add data from the dictionary evenly to all the rows in my framework. I am currently sorting through a dictionary and setting a value for my new columns. Is there a more efficient way to do this?

notebook

# coding: utf-8    
import pandas as pd

df = pd.DataFrame({'age' : [1, 2, 3],'name' : ['Foo', 'Bar', 'Barbie']}) 
d = {"blah":42,"blah-blah":"bar"}
for k,v in d.items():
    df[k] = v
df
+4
source share
2 answers

Use assignif all keys are not numeric:

df = df.assign(**d)
print (df)
   age    name  blah blah-blah
0    1     Foo    42       bar
1    2     Bar    42       bar
2    3  Barbie    42       bar

If possible, numeric joinworks well:

d = {8:42,"blah-blah":"bar"}
df = df.join(pd.DataFrame(d, index=df.index))
print (df)

   age    name   8 blah-blah
0    1     Foo  42       bar
1    2     Bar  42       bar
2    3  Barbie  42       bar
+3
source

, , . , dict , df[k] = v . , , - , , . , , , .

d = {"blah":42,"blah-blah":"bar"}

# Add columns to compensate for missing values in document XXX
for k,v in d.items():
    df[k] = v

( ... , ):

:

809 µs ± 70 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

df.assign():

893 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
+2

Source: https://habr.com/ru/post/1696154/


All Articles