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

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)

其他回答

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

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

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

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

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

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

你需要提供可迭代对象作为Pandas DataFrame列的值:

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

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