简体   繁体   中英

Pandas column of list of keys and column of list of values to a column of a list of dictionaries

I have a pandas dataframe, one column contains data values of type list of strings. Another column contains data values of type list of integer. This might look like

           keys             values
0  ['key1','key2','key3']  [0,1,2]
1  ['key1','key2','key3']  [4,5,6]
2  ['key2','key1','key3']  [7,3,6] 

What I would like to do is have a column of dictionary type values in which eg,

           keys             values               dicts
0  ['key1','key2','key3']  [0,1,2]   {'key1':0,'key2':1,'key3':3}
1  ['key1','key2','key3']  [4,5,6]   {'key1':4,'key2':5,'key3':6}
2  ['key2','key1','key3']  [7,3,6]   {'key2':7,'key1':3,'key3':6} 

Assume that both lists across the two column are ordered such that df['keys'][0][0] would correspond to df['values'][0][0] etc.

What I would ideally like to do a brief dict comprehension to achieve this. My thought process has led me to attempt something along the lines of:

df['dicts'] = {k:v for (k,v) in [x for x in zip(df['keys'], df['values'])]}

Which did not succeed, producing a type error:

<Ipython-input-416-0c2823a27ccf> in <module>
----> 1 df['dicts']= dict(zip(df['keys'], df['values']))

TypeError: unhashable type: 'list'

As well as:

df['dicts']= dict(zip(df['keys'], df['values']))

Which fails, producing the following type error:

<Ipython-input-416-0c2823a27ccf> in <module>
----> 1 df['dicts']= dict(zip(df['keys'], df['values']))

TypeError: unhashable type: 'list'

Try:

df['dicts'] = [dict(zip(x,y)) for x,y in zip(df['keys'], df['values'])]

Or with unpack:

df['dicts'] = [dict(zip(*u)) for u in zip(df['keys'], df['values'])]

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