2

How can I take a string and create a data frame.

Let's say the string I have is the following.

ss = "This is a string"

If I do the following, it produced an error.

pd.DataFrame(ss)
Traceback (most recent call last):

  File "<ipython-input-84-4694a8452254>", line 1, in <module>
    pd.DataFrame(ss)

  File "/Users/abrahammathew/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 404, in __init__
    raise ValueError('DataFrame constructor not properly called!')

ValueError: DataFrame constructor not properly called!

However, if I try to create a series, it works.

pd.Series(ss)
Out[85]: 
0    This is a string
dtype: object
3
  • pd.Series(ss).to_frame() Commented Jun 4, 2018 at 22:50
  • or pd.DataFrame([ss]) Commented Jun 4, 2018 at 22:51
  • What is your expected output? Commented Jun 4, 2018 at 22:53

2 Answers 2

2

Try the below:

from pandas.compat import StringIO
df_string= pd.read_csv(StringIO(ss), sep=';')

Or:

df_string=pd.DataFrame(pd.Series(ss))
Sign up to request clarification or add additional context in comments.

Comments

1

You can see a DataFrame as a 2D thing (while a Series would be 1D). In order to have a proper DataFrame, pandas needs index or columns or some dimension. Try the following:

>>> pd.DataFrame(["Hello"])
       0
0  Hello

I wonder why you'd need this.

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.