Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting comma separated string with key-value form into pandas Dataframe

I would like to convert the following string into a pandas dataframe:

data = "key=iApFK, age=58, key=234das, age=64, key=89snkj, age=47"

The dataframe would look like this:

            key        age    
0           iApFK      58  
1           234das     64
2           89snkj     47

I tried doing it with pandas.read_csv and io.SringIO but I am confused regarding the extraction of the values and the delimiter. Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

pd.DataFrame(re.findall("key=(\w+), age=(\w+),?", data), columns=["key", "age"])

you can find fields with re.findall, then pass the result to pd.DataFrame along with the column names:

In [32]: data
Out[32]: 'key=iApFK, age=58, key=234das, age=64, key=89snkj, age=47'

In [33]: re.findall("key=(\w+), age=(\w+),?", data)
Out[33]: [('iApFK', '58'), ('234das', '64'), ('89snkj', '47')]

In [34]: pd.DataFrame(re.findall("key=(\w+), age=(\w+),?", data), columns=["key", "age"])
Out[34]:
      key age
0   iApFK  58
1  234das  64
2  89snkj  47
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading