简体   繁体   中英

Convert pandas DataFrame to dict where each value is a list of values of multiple columns

Let's say I have the DataFrame

filename size inverse similarity
123.txt  1    2       34
323.txt  3    1       44
222.txt  4    1       43

I want to create a dictionary in the form

{'123.txt': [1, 2, 34],
 '323.txt': [3, 1, 44],
 '222.txt': [4, 1, 43]}

Solutions I have found deal with the case of creating a dict with single values using something like

df.set_index('Filename')['size'].to_dict()

Set 'filename' as the index, take the transpose, then use to_dict with orient='list' :

my_dict = df.set_index('filename').T.to_dict(orient='list')

The resulting output:

{'323.txt': [3, 1, 44], '222.txt': [4, 1, 43], '123.txt': [1, 2, 34]}

Here's an approach with dict comprehension:

{k: v for k, v in zip(df['filename'], df.set_index('filename').values.tolist())}
Out: {'123.txt': [1, 2, 34], '222.txt': [4, 1, 43], '323.txt': [3, 1, 44]}

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