Home > Blockchain >  Convert a string into dataframe in python?
Convert a string into dataframe in python?

Time:08-13

I have a string which looks like this.

x = 24.55 26.22, 69.22 78.25, 66.25 45.98

I want to convert into a dataframe which looks like this:

  A       B      A     B      A      B
24.55   26.22  69.22  78.25  66.25  45.98

This is what I have tried but iam getting an error

import io
import pandas as pd
df1 = pd.read_csv(io.StringIO(x), sep=",")
df1 =  df1.groupby(level=[0,1]).cumcount().map({0 : 'x', 1 : 'y'})

CodePudding user response:

You could use a double split, stack and reshape to DataFrame:

x = '24.55 26.22, 69.22 78.25, 66.25 45.98'

out = (pd
       .DataFrame([map(float, s.split()) for s in x.split(',')],
                  columns=['A', 'B'])
       .stack().droplevel(0)
       .to_frame().T
      )

output:

       A      B      A      B      A      B
0  24.55  26.22  69.22  78.25  66.25  45.98

If you already know the number of items:

pd.DataFrame([[float(e) for s in x.split(',') for e in s.split()]],
             columns=['A', 'B']*3)
  • Related