I want to dump a two-columns dataframe into a dictionary like this:
My dataframe:
df['col1'] = pd.Series(['id_1','id_2','id_3','id_4'])
df['col2'] = pd.Series(['Name1','Name2','Name3','Name4'])
Desired dictionary
dict = {'id_1':'Name1','id_2':'Name2','id_3':'Name3',...}
What would be a nice way of doing this without looping through the rows?
Use df.set_index()
to set the dictionary keys and take only the column you want as values and call series.to_dict()
on it:
my_dict=df.set_index('col1')['col2'].to_dict()
Or you can use zip
to zip
2 columns and call the dict
function on it.
my_dict=dict(zip(df.col1,df.col2))
Output:
{'id_1': 'Name1', 'id_2': 'Name2', 'id_3': 'Name3', 'id_4': 'Name4'}
PS Don't use dict
as a dictionary name since it is a python builtin func.
Another way is calling dict
directly on numpy array of df
.
If your df
has exact 2 columns:
dict(df.values)
If your df
has more than 2 columns, just slicing 2 columns you want to convert and call dict
on them:
dict(df[['col1', 'col2']].values)
Output:
{'id_1': 'Name1', 'id_2': 'Name2', 'id_3': 'Name3', 'id_4': 'Name4'}
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.