Convert Dataframe to a Dictionary with List Values

2024/10/11 4:30:32

Suppose I have a Dataframe df :

Label1    Label2        Label3
key1      col1value1    col2value1
key2      col1value2    col2value2
key3      col1value3    col2value3dict1 = df.set_index('Label1').to_dict() 

This works when we have 2 columns..

Expected Output:

my_dict = {key1: [col1value1,col2value1] , key2: [ col1value2,col2value2] , key3:[col1value3,col2value3] }

Can I use to_dict on Dataframe df to have a key with 2 other columns as values in form of list ??

Answer

Well you could use a dictionary comprehension and iterrows:

print {key:row.tolist() for key,row in df.set_index('Label1').iterrows()}{'key3': ['col1value3', 'col2value3'],'key2': ['col1value2', 'col2value2'], 'key1': ['col1value1', 'col2value1']}

Also, I think the following will work too:

df = df.set_index('Label1')
print df.T.to_dict(outtype='list'){'key3': ['col1value3', 'col2value3'],'key2': ['col1value2', 'col2value2'],'key1': ['col1value1', 'col2value1']}

Update as of fall 2017; outtype is no longer the keyword argument. Use orient instead:

In [11]: df.T.to_dict(orient='list')
Out[11]: 
{'key1': ['col1value1', 'col2value1'],'key2': ['col1value2', 'col2value2'],'key3': ['col1value3', 'col2value3']}
https://en.xdnf.cn/q/69812.html

Related Q&A

Efficiently count all the combinations of numbers having a sum close to 0

I have following pandas dataframe df column1 column2 list_numbers sublist_column x y [10,-6,1,-4] a b [1,3,7,-2] p q [6,2,-3,-3.…

What is the equivalent to iloc for dask dataframe?

I have a situation where I need to index a dask dataframe by location. I see that there is not an .iloc method available. Is there an alternative? Or am I required to use label-based indexing?For …

How to deal with limitations of inspect.getsource - or how to get ONLY the source of a function?

I have been playing with the inspect module from Pythons standard library. The following examples work just fine (assuming that inspect has been imported):def foo(x, y):return x - y print(inspect.getso…

Checking whether a function is decorated

I am trying to build a control structure in a class method that takes a function as input and has different behaviors if a function is decorated or not. Any ideas on how you would go about building a f…

How to keep the script run after plt.show() [duplicate]

This question already has answers here:Is there a way to detach matplotlib plots so that the computation can continue?(21 answers)Closed 6 years ago.After the plt.show() , I just want to continue. How…

python - Simulating else in dictionary switch statements

Im working on a project which used a load of If, Elif, Elif, ...Else structures, which I later changed for switch-like statements, as shown here and here.How would I go about adding a general "Hey…

Allow dynamic choice in Django ChoiceField

Im using Select2 in my application for creating tags-like select dropdowns. Users can select number of predefined tags or create a new tag.Relevant forms class part:all_tags = Tag.objects.values_list(i…

Row-wise unions in pandas groupby

I have a large data frame that looks like so (and is copy-pasteable with df=pd.read_clipboard(sep=\s\s+):user_nm month unique_ips shifted_ips halves quarters mo_pairs100118231 2 set(…

Add seaborn.palplot axes to existing figure for visualisation of different color palettes

Adding seaborn figures to subplots is usually done by passing ax when creating the figure. For instance:sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=ax)This method, however, doesnt apply to seabo…

Running Django with Run can not find LESS CSS

I have a Django project that uses buildout. When running or debugging the application it runs fine by using my buildout script. I also use django-compressor to compress and compile my LESS files. I ins…