简体   繁体   中英

How can I add column values from a pandas dataframe as a new key value pair in another column having dictionary?

I have a dataframe for example

df = {'dicts':[{'id': 0, 'text': 'Willamette'},
{'id': 1, 'text': 'Valley'}],
 'ner': ["Person", "Location"]}
df= pd.DataFrame(df)

` I want end result like

{'id': 0, 'text': 'Willamette', 'ner': 'Person'}
{'id': 1, 'text': 'Valley', 'ner': 'Location'}

`

I am using following logic but it isn't working for me-

for i, rows in df["dicts"].iteritems():
   for cat in df['ner']:
    df["dicts"][i]=df["dicts"][i].update({'ner' : df['ner'][cat]})

How can i solve this?

IIUC

d=pd.DataFrame(df.dicts.tolist(),index=df.index).join(df[['ner']]).to_dict('r')
[{'id': 0, 'text': 'Willamette', 'ner': 'Person'}, {'id': 1, 'text': 'Valley', 'ner': 'Location'}]

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