Home > Software engineering >  How to change python string into pandas data frame?
How to change python string into pandas data frame?

Time:03-24

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

CodePudding user response:

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)

CodePudding user response:

You can try this:

import pandas as pd
str_stream = 'key=apple; age=10; key=boy; age=3'
lst_kv = str_stream.split(';')   
# lst_kv => ['key=apple', ' age=10', ' key=boy', ' age=3']

res= [{s.split('=')[0].strip(): s.split('=')[1] for s in lst_kv[i:i 2]} 
      for i in range(len(lst_kv)//2)
     ]
df = pd.DataFrame(res)
df

Output:

    key     age
0   apple   10
1   boy     10

More explanation for one line res :

res = []
for i in range(len(lst_kv)//2):
    dct_tmp = {}
    for s in lst_kv[i:i 2]:
        kv = s.split('=')
        dct_tmp[kv[0].strip()] = kv[1]
    res.append(dct_tmp)
res

Output:

[{'key': 'apple', 'age': '10'}, {'age': '10', 'key': 'boy'}]
  • Related