将标量的字典转换为 Pandas DataFrame

Pie*_* S. 5 dictionary python-3.x pandas

在 Python3 下,我有一个格式如下的字典:

my_dict = {'col1': 1.0, 'col2':2.0, 'col3': 3.0}
Run Code Online (Sandbox Code Playgroud)

我想使用 dict 键作为列将其转换为 Pandas DataFrame:

      col1  col2  col3
0     1.0   2.0   3.0
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试以下命令时,出现 ValueError:

df = pd.DataFrame(my_dict)

ValueError: If using all scalar values, you must pass an index
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

用:

df = pd.DataFrame([my_dict])
Run Code Online (Sandbox Code Playgroud)

或者:

df = pd.DataFrame.from_dict(my_dict, orient='index').T
Run Code Online (Sandbox Code Playgroud)

或者:

df = pd.DataFrame(my_dict, index=[0])
Run Code Online (Sandbox Code Playgroud)
print (df)
   col1  col2  col3
0   1.0   2.0   3.0
Run Code Online (Sandbox Code Playgroud)

  • 您会推荐哪一个,为什么?:) (2认同)