Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dataframe to dictionary in pandas WITHOUT index

I have a dataframe df as follows:

| name  | coverage | |-------|----------| | Jason | 25.1     | 

I want to convert it to a dictionary. I used the following command in pandas :

dict=df.to_dict() 

The output of dict gave me the following:

{'coverage': {0: 25.1}, 'name': {0: 'Jason'}}  

I do not want the 0 in my output. I believe this is captured because of the column index in my dataframe df. What can I do to eliminate 0 in my output ( I do not want index to be captured.) expected output :

{'coverage': 25.1, 'name': 'Jason'}  
like image 666
Symphony Avatar asked Sep 28 '18 03:09

Symphony


People also ask

How do I convert a Pandas DataFrame to a dictionary?

To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.

How do I get rid of pandas indexing?

The most straightforward way to drop a Pandas dataframe index is to use the Pandas . reset_index() method. By default, the method will only reset the index, forcing values from 0 - len(df)-1 as the index.

How do you convert a dataset to a dictionary in python?

to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter. Parameters: orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).

How do you turn a pandas show into a dictionary?

to_dict() function is used to convert the given Series object to {label -> value} dict or dict-like object.


1 Answers

When I see your dataset with 2 columns I see a series and not a dataframe.

Try this: d = df.set_index('name')['coverage'].to_dict() which will convert your dataframe to a series and output that.

However, if your intent is to have more columns and not a common key you could store them in an array instead using 'records'. d = df.to_dict('r'). `

Runnable code:

import pandas as pd  df = pd.DataFrame({     'name': ['Jason'],     'coverage': [25.1] })  print(df.to_dict()) print(df.set_index('name')['coverage'].to_dict()) print(df.to_dict('r')) 

Returns:

{'name': {0: 'Jason'}, 'coverage': {0: 25.1}} {'Jason': 25.1} [{'name': 'Jason', 'coverage': 25.1}] 

And one more thing, try to avoid to use variable name dict as it is reserved.

like image 59
Anton vBR Avatar answered Oct 02 '22 01:10

Anton vBR