3

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

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

beautiful ... this is exactly what I was looking for
3

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

1 Comment

Had the same idea!
1

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

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.