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

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)

其他回答

你可以试试这个: df2 = pd.DataFrame.from_dict ({a: a、b: b},东方=“指数”)

你也可以使用pd.DataFrame.from_records,这在你已经有字典的情况下更方便:

df = pd.DataFrame.from_records([{ 'A':a,'B':b }])

你也可以设置索引,如果你想,通过:

df = pd.DataFrame.from_records([{ 'A':a,'B':b }], index='A')

我通常使用以下方法从字典快速创建一个小表。

假设你有一个dict,其中键是文件名,值是对应的文件大小,你可以使用以下代码将它放入一个DataFrame(注意dict上的.items()调用):

files = {'A.txt':12, 'B.txt':34, 'C.txt':56, 'D.txt':78}
filesFrame = pd.DataFrame(files.items(), columns=['filename','size'])
print(filesFrame)

  filename  size
0    A.txt    12
1    B.txt    34
2    C.txt    56
3    D.txt    78

如果你有一个字典,你可以用下面这行代码把它转换成pandas数据帧:

pd.DataFrame({"key": d.keys(), "value": d.values()})

最简单的选项ls:

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