Markus Dutschke
Markus Dutschke

Reputation: 10606

python: write a dictionary into a pandas.DataFrame row

I am looking for a one-liner solution to write a dictionary into a pandas DataFrame row. The other way round works quite intuively with an expression like df.loc[2, :].to_dict(dct).

Illustration

I am looking for a shot expression to replace the for key in dct.keys()-loop in the following code:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.arange(12).reshape(3,4), columns=list('abcd'))
>>> dct = {'a': 77, 'c':-1}
>>> 
>>> df
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
>>> dct
{'a': 77, 'c': -1}
>>> 
>>> for key in dct.keys():
...     df.loc[1, key] = dct[key]
... 
>>> 
>>> df
    a  b   c   d
0   0  1   2   3
1  77  5  -1   7
2   8  9  10  11

Upvotes: 3

Views: 1035

Answers (3)

Markus Dutschke
Markus Dutschke

Reputation: 10606

if your columns dtype is object

the accepted answer fails, if df.dtype is object. You need an additional cast to list on the right handside of the df.loc[1, dct.keys()] = dct.values() assignment.

df.update(pd.DataFrame(dct, index=[1])) works for this case.

>>> import pandas as pd
>>> df = pd.DataFrame([['A', 'B', 'C'], ['D', 'E', 'F']], columns=list('abc'))
>>> df.dtypes
a    object
b    object
c    object
dtype: object
>>> df
   a  b  c
0  A  B  C
1  D  E  F
>>> dct = {'a': 'x', 'c': 'y'}
>>> df.loc[1, dct.keys()] = dct.values()
>>> df
        a  b       c
0       A  B       C
1  (x, y)  E  (x, y)
>>> df.loc[1, dct.keys()] = list(dct.values())
>>> df
   a  b  c
0  A  B  C
1  x  E  y

Upvotes: 1

jezrael
jezrael

Reputation: 862671

One idea with DataFrame.update:

df.update(pd.DataFrame(dct, index=[1]))

print (df)
      a  b     c   d
0   0.0  1   2.0   3
1  77.0  5  -1.0   7
2   8.0  9  10.0  11

Upvotes: 3

Shubham Sharma
Shubham Sharma

Reputation: 71689

You can use:

df.loc[1, dct.keys()] = dct.values()

Result:

print(df)
    a  b   c   d
0   0  1   2   3
1  77  5  -1   7
2   8  9  10  11

Upvotes: 7

Related Questions