简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM