Under Python3, I have a dict with the following format:
my_dict = {'col1': 1.0, 'col2':2.0, 'col3': 3.0}
And I want to convert it to a pandas DataFrame using dict keys as columns:
col1 col2 col3
0 1.0 2.0 3.0
However, when I try the following command I have a ValueError:
df = pd.DataFrame(my_dict)
ValueError: If using all scalar values, you must pass an index
You can convert a dictionary to Pandas Dataframe using df = pd. DataFrame. from_dict(my_dict) statement.
Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.
We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.
For certain small, targeted purposes, a dict may be faster. And if that is all you need, then use a dict, for sure! But if you need/want the power and luxury of a DataFrame, then a dict is no substitute.
Use:
df = pd.DataFrame([my_dict])
Or:
df = pd.DataFrame.from_dict(my_dict, orient='index').T
Or:
df = pd.DataFrame(my_dict, index=[0])
print (df)
col1 col2 col3
0 1.0 2.0 3.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With