Constructing Pandas Dataframe From Values In Variables Gives "valueerror: If Using All Scalar Values, You Must Pass An Index"
Solution 1:
The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:
>>>df = pd.DataFrame({'A': [a], 'B': [b]})>>>df
A B
0 2 3
or use scalar values and pass an index:
>>>df = pd.DataFrame({'A': a, 'B': b}, index=[0])>>>df
A B
0 2 3
Solution 2:
You can also use pd.DataFrame.from_records
which is more convenient when you already have the dictionary in hand:
df = pd.DataFrame.from_records([{ 'A':a,'B':b }])
You can also set index, if you want, by:
df = pd.DataFrame.from_records([{ 'A':a,'B':b }], index='A')
Solution 3:
You may try wrapping your dictionary into a list:
my_dict = {'A':1,'B':2}
pd.DataFrame([my_dict])
AB012
Solution 4:
You need to create a pandas series first. The second step is to convert the pandas series to pandas dataframe.
import pandas as pd
data = {'a': 1, 'b': 2}
pd.Series(data).to_frame()
You can even provide a column name.
pd.Series(data).to_frame('ColumnName')
Solution 5:
Maybe Series would provide all the functions you need:
pd.Series({'A':a,'B':b})
DataFrame can be thought of as a collection of Series hence you can :
Concatenate multiple Series into one data frame (as described here )
Add a Series variable into existing data frame ( example here )
Post a Comment for "Constructing Pandas Dataframe From Values In Variables Gives "valueerror: If Using All Scalar Values, You Must Pass An Index""