0

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 I am 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'})
1
  • What error do you get? What is the exact error message? Can you add it to your question? (But ******** without ******** "Edit:", "Update:", or similar - the question should appear as if it was written today) Commented Oct 21, 2022 at 14:35

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.