2

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}
Rory
  • 471
  • 2
  • 11
  • 5
    This `{'sc': 3, 'delhi': 2, 'sonepat', 'delhi': 1, 'new delhi': 1, }` is not a dictionary. Also please also share your DataFrame in such a way it can be copied into a Python script, for example df.to_dict() – Dani Mesejo Oct 27 '21 at 22:47
  • I edit my question – Rory Oct 27 '21 at 22:58
  • 1
    Is the same, you cannot have `sonepat` as single string in the dictionary – Dani Mesejo Oct 27 '21 at 22:59
  • I don't really understand, I got this dataframe because I counted unique values, so I have this output – Rory Oct 27 '21 at 23:02
  • Please take a look at [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). It provides advice about how to make your question easier to answer. – Nick ODell Oct 27 '21 at 23:02

1 Answers1

2

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, "...
Laurent
  • 12,287
  • 7
  • 21
  • 37