Python common error: if using all scalar values, you must pass an index (four solutions)

(author: Chen’s freebies)

1, error scenario:

import pandas as pd
dict = {'a':1,'b':2,'c':3}
data = pd.DataFrame(dict)

2, error reason:

The dictionary

is passed in directly with the nominal attribute value and index is required, that is, index is set when the DataFrame object is created.

3, solution:

Creating DataFrame objects with a

dictionary is a common requirement, but it can be written differently depending on the object form. Look at the code, the following four methods can correct this error, and produce the same correct results, which method to use according to your own needs.

import pandas as pd

#方法一:直接在创建DataFrame时设置index即可
dict = {'a':1,'b':2,'c':3}
data = pd.DataFrame(dict,index=[0])
print(data)

#方法二:通过from_dict函数将value为标称变量的字典转换为DataFrame对象
dict = {'a':1,'b':2,'c':3}
pd.DataFrame.from_dict(dict,orient='index').T
print(data)

#方法三:输入字典时不要让Value为标称属性,把Value转换为list对象再传入即可
dict = {'a':[1],'b':[2],'c':[3]}
data = pd.DataFrame(dict)
print(data)

#方法四:直接将key和value取出来,都转换成list对象
dict = {'a':1,'b':2,'c':3}
pd.DataFrame(list(dict.items()))
print(data)

Read More: