[SOLVED] How to change python string into pandas data frame?

Issue

fellow developers in the StackOverflow.
I have string data in
'key=apple; age=10; key=boy; age=3'
How can we convert it into the pandas’ data frame such that key and age will be the header and all the values in the column?

key   age
apple 10
boy   3

Solution

Try this:

import pandas as pd

data = 'key=apple; age=10; key=boy; age=3'
words = data.split(";")
key = []
age = []

for word in words:
    if "key" in word:
        key.append(word.split("=")[1])
    else:
        age.append(word.split("=")[1])

df = pd.DataFrame(key, columns=["key"])
df["age"] = age

print(df)

Answered By – Tomer S

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *