Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16388

How to convert pandas DataFrame into a dictionary with specific column as key that contains duplicate value?

$
0
0

I want to convert DataFrames into dictionaries. I have a column to use as the key, and other columns should be represented as a list of values for each key. However, I have duplicate values in key columns.

Here is an example DataFrame:

import pandas as pddf = pd.DataFrame({'SL': ['1', '2', '3', '4', '5'],'SITECODE': ['CMCND1', 'CPHGN7', 'LXRPR1', 'LXRPR1', 'LXRPR1'],'TECH': ['3G', '2G', '4G', '3G', '4G'],'PRIORITY': ['P1', 'P2', 'P2', 'P3', 'P3']})

Desired Output and key column name is 'SITECODE'

{'CMCND1': ['1', '3G', 'P1'],'CPHGN7': ['2', '2G', 'P2'],'LXRPR1': ['3', '4G', 'P2'],['4', '3G', 'P3'],['5', '4G', 'P3']}

I have tried using the following formula, but it does not give me the desired output.

df.set_index('SITECODE').T.to_dict('list')

it doesn't group the duplicate keys together.


Viewing all articles
Browse latest Browse all 16388

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>