这可能是一个简单的问题,但我不知道该怎么做。假设有两个变量。

a = 2
b = 3

我想从这个构建一个数据框架:

df2 = pd.DataFrame({'A':a,'B':b})

这会产生一个错误:

ValueError:如果使用所有标量值,则必须传递一个索引

我也试过这个:

df2 = (pd.DataFrame({'a':a,'b':b})).reset_index()

这将给出相同的错误消息。


当前回答

如果你想转换一个标量字典,你必须包含一个索引:

import pandas as pd

alphabets = {'A': 'a', 'B': 'b'}
index = [0]
alphabets_df = pd.DataFrame(alphabets, index=index)
print(alphabets_df)

虽然索引对于列表字典不需要,但同样的思想可以扩展到列表字典:

planets = {'planet': ['earth', 'mars', 'jupiter'], 'length_of_day': ['1', '1.03', '0.414']}
index = [0, 1, 2]
planets_df = pd.DataFrame(planets, index=index)
print(planets_df)

当然,对于列表字典,你可以在没有索引的情况下构建数据框架:

planets_df = pd.DataFrame(planets)
print(planets_df)

其他回答

将“a”和“b”值更改为列表,如下所示:

a = [2]
b = [3]

然后执行如下代码:

df2 = pd.DataFrame({'A':a,'B':b})
df2

你会得到:

    A   B
0   2   3

如果你想转换一个标量字典,你必须包含一个索引:

import pandas as pd

alphabets = {'A': 'a', 'B': 'b'}
index = [0]
alphabets_df = pd.DataFrame(alphabets, index=index)
print(alphabets_df)

虽然索引对于列表字典不需要,但同样的思想可以扩展到列表字典:

planets = {'planet': ['earth', 'mars', 'jupiter'], 'length_of_day': ['1', '1.03', '0.414']}
index = [0, 1, 2]
planets_df = pd.DataFrame(planets, index=index)
print(planets_df)

当然,对于列表字典,你可以在没有索引的情况下构建数据框架:

planets_df = pd.DataFrame(planets)
print(planets_df)

你可以试试:

df2 = pd.DataFrame.from_dict({'a':a,'b':b}, orient = 'index')

来自'orient'参数的文档:如果传递的dict的键应该是结果DataFrame的列,则传递' columns '(默认)。否则,如果键应该是行,则传递' index '。

最简单的选项ls:

dict  = {'A':a,'B':b}
df = pd.DataFrame(dict, index = np.arange(1) )

你可以试着把你的字典包装成一个列表:

my_dict = {'A':1,'B':2}
pd.DataFrame([my_dict])
   A  B
0  1  2