Get a row of data in pandas as a dict

pandas to_dict
pandas dataframe to dict two columns
pandas series to dict
pandas unpack dictionary
convert dataframe to dictionary with one column as key
python pandas convert dataframe to dictionary with multiple values
how to make a dictionary out of a pandas dataframe
pandas itertuples to dict

To get a row of data in pandas by index I can do:


Is there a way to get that row of data as a dict, other than doing:

    df.loc[100], tolist()

You will run into a problem if you have columns with non-unique names.


>>> df = pd.DataFrame([[1,2,3,4,5], [6,7,8,9,10]], columns=['A', 'B', 'A', 'C', 'B'])                                     
>>> df                                                                                                                 
   A  B  A  C   B
0  1  2  3  4   5
1  6  7  8  9  10
>>> df.loc[1].to_dict()                                                                                                
{'A': 8, 'B': 10, 'C': 9}

If this can happen in your dataframe, make the columns unique before creating the dict.

Here's an idea to do so:

>>> from itertools import count 
>>> col_isdupe = zip(df.columns, df.columns.duplicated(keep=False))                                                    
>>> counters = {c:count() for c, dupe in col_isdupe if dupe}                                                           
>>> df.columns = ['{}_{}'.format(c, next(counters[c])) if c in counters else c 
...:              for c in df.columns]                               
>>> df                                                                                                                 
   A_0  B_0  A_1  C  B_1
0    1    2    3  4    5
1    6    7    8  9   10
>>> df.loc[1].to_dict()                                                                                                
{'A_0': 6, 'A_1': 8, 'B_0': 7, 'B_1': 10, 'C': 9}

pandas.DataFrame.to_dict, pandas.DataFrame.to_dict¶. DataFrame. to_dict (self, orient='dict', into=<class '​dict'>)[source]¶. Convert the DataFrame to a dictionary. The type of the key-value​  We are setting the Name column as our index. See the following code. # import pandas as pd df = pd.read_csv ( 'people.csv' ) df.set_index ( "Name", inplace= True) Now, we can select any label from the Name column in DataFrame to get the row for the particular label.

Try with to_dict


How to convert a Pandas DataFrame into a dictionary in Python, A Pandas DataFrame is a data store with rows and columns. Converting a DataFrame to a dictionary creates a mapping where each row is a key-value pair with  I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in same row be values.

You can use items:


Export pandas to dictionary by combining multiple row values, How do I get my desired output? Is there a way to aggregate all the values for the same name column and get them in the form I want? For example, I have DataFrame now as id score1 score2 score3 score4 score5 1 0.000000 0.108659 0.000000 0.078597 1 2 0.053238 0.308253 0.286353 0.446433 1 3 0.00

df.loc[x] returns a mapping, a pd.Series, so you can just use the dict constructor directly:


Or the to_dict helper method if you prefer...

This sort of raises the question, are you sure you need a dict at all?

Make column as dictionary key and row as value in pandas dataframe, orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into). For example, 'list' would return a dictionary of  Let’s now review additional examples to get a better sense of selecting rows from a pandas DataFrame. Example 1: Select rows where the price is equal or greater than 10. To get all the rows where the price is equal or greater than 10, you’ll need to apply this condition: df.loc[df[‘Price’] >= 10] And this is the complete Python code:

Say your dataframe is df and you want the row with index k, you can do:


The result will be a list of all the values in row k.

Python, from pandas import DataFrame my_dict = {key:value,key:value,key:value,} df = DataFrame(list(my_dict.items()),columns = ['column1','column2']). In this short Run the code in Python, and you'll get this dictionary: Dictionary  pandas.DataFrame.to_dict¶ DataFrame.to_dict (self, orient='dict', into=<class 'dict'>) [source] ¶ Convert the DataFrame to a dictionary. The type of the key-value pairs can be customized with the parameters (see below).

How to Convert Dictionary to Pandas DataFrame, Let's create a dataframe first with three columns Name, Age and City and just to keep things simpler we will have 4 rows in this Dataframe. data dict. Of the form {field : array-like} or {field : dict}. orient {‘columns’, ‘index’}, default ‘columns’ The “orientation” of the data. If the keys of the passed dict should be the columns of the resulting DataFrame, pass ‘columns’ (default). Otherwise if the keys should be rows, pass ‘index’. dtype dtype, default None

Convert Pandas dataframe to dictionary, Here is a pandas cheat sheet of the most common data operations in pandas. pandas-from-dict Values. Get the value of a column on a row with index idx:. Extracting specific rows of a pandas dataframe ¶. df2 [1:3] df2[1:3] df2 [1:3] That would return the row with index 1, and 2. The row with index 3 is not included in the extract because that’s how the slicing syntax works. Note also that row with index 1 is the second row. Row with index 2 is the third row and so on.

Pandas cheat sheet, Now suppose we have a dictionary containing the rows of a DataFrame. We can import this data using the orient='index' option: import pandas  Indexing and selecting data¶ The axis labeling information in pandas objects serves many purposes: Identifies data (i.e. provides metadata) using known indicators, important for analysis, visualization, and interactive console display. Enables automatic and explicit data alignment. Allows intuitive getting and setting of subsets of the data set.

  • got it, I think I was probably thrown off by the tolist not having an underscore in it so I thought that method didn't exist.
  • @David542 when I first touch pandas I have the same question , why list : tolist and dict is to_dict. :-)(just the way they name the functions )
  • @David542 yeah... it's not particularly consistent... I think it's mostly that .tolist() is what's used for numpy arrays and to_dict is just pandas... By keeping with .tolist() you don't have to worry about determining if you're dealing with a Series or a 1D array.