Jesper - jtk.eth
Jesper - jtk.eth

Reputation: 7484

How to use dtype argument in Panda's from_dict (Python)

I have a dictionary:

d = {1: 'hello'}

I want to turn this into a Panda's dataframe (so a dataframe with strings as row values).

I am looking at: pd.DataFrame.from_dict(d, orient='columns', dtype=???)

If I leave out the "dtype" argument I get:

ValueError: If using all scalar values, you must pass an index

Using "orient='columns'" means using the keys as columns. But how do I use the dtype then (I assume the error is due to the num/string issue)?

Answer summarized: Construct "d" as:

d = {1: ['hello']}

Then use:

pd.DataFrame.from_dict(d)

Thank you

Upvotes: 1

Views: 1711

Answers (1)

Alexander
Alexander

Reputation: 109696

You need to bracket 'hello' if passed without the index.

>>> pd.DataFrame.from_dict({1: ['hello']}, orient='columns', dtype=str)
       1
0  hello

Note that 'columns' is the default value for orient and is not required. Also, the dtype will be inferred if not given explicitly.

Upvotes: 1

Related Questions