Home > OS >  How to convert a dictionary with lists to a different kind of dictionary for a column
How to convert a dictionary with lists to a different kind of dictionary for a column

Time:10-29

I have a dataframe like this:

import pandas as pd
    frame={'location': {(2, 'eng', 'US'): {"['sc']": 3, "['delhi']": 2, "['sonepat', 'delhi']": 1, "['new delhi']": 1}}}
    df=pd.DataFrame(frame)
    df.head()

Output

                            location
2       eng       US    {"['sc']": 3, "['delhi']": 2, "['sonepat', 'delhi']": 1, "['new delhi']": 1}

  

And i want to change the type inside the column df['location'] to not list, like :

                            location
2       eng       US    {'sc': 3, 'delhi': 2, 'sonepat', 'delhi': 1, 'new delhi': 1}

CodePudding user response:

You could try this:

import pandas as pd


df = pd.DataFrame(
    {
        "location": {
            (2, "eng", "US"): {
                "['sc']": 3,
                "['delhi']": 2,
                "['sonepat', 'delhi']": 1,
                "['new delhi']": 1,
            }
        }
    }
)

df["location"] = df["location"].apply(
    lambda x: str(x).replace("['", "").replace("']", "")
)

print(df)
#Outputs
                                                   location
2 eng US  {"sc": 3, "delhi": 2, "sonepat', 'delhi": 1, "...
  • Related