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

a = 2
b = 3

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

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

这会产生一个错误:

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

我也试过这个:

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

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


当前回答

只要把字典放在一个列表上:

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

其他回答

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

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 = 2
b = 3
df2 = pd.DataFrame([{'A':a,'B':b}])

首先你需要创造一个熊猫系列。第二步是将pandas系列转换为pandas数据框架。

import pandas as pd
data = {'a': 1, 'b': 2}
pd.Series(data).to_frame()

您甚至可以提供列名。

pd.Series(data).to_frame('ColumnName')

最简单的选项ls:

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

pd.DataFrame(pd.Series(dict)).T  
# *T :transforms the dataframe*

   Result:
    A   B
0   2   3