从变量中的值构造 DataFrame 会产生“ValueError: 如果使用所有标量值,则必须传递索引”
- 2025-01-14 08:50:00
- admin 原创
- 79
问题描述:
我有两个变量如下。
a = 2
b = 3
我想从中构建一个 DataFrame:
df2 = pd.DataFrame({'A':a, 'B':b})
这会产生一个错误:
ValueError: If using all scalar values, you must pass an index
我也尝试过这个:
df2 = (pd.DataFrame({'a':a, 'b':b})).reset_index()
这给出了相同的错误消息。我该怎么做?
解决方案 1:
错误消息表明,如果您传递标量值,则必须传递索引。因此,您可以不对列使用标量值——例如使用列表:
>>> df = pd.DataFrame({'A': [a], 'B': [b]})
>>> df
A B
0 2 3
或者使用标量值并传递索引:
>>> df = pd.DataFrame({'A': a, 'B': b}, index=[0, 3])
>>> df
A B
0 2 3
3 2 3
解决方案 2:
您可以尝试将字典包装到列表中:
my_dict = {'A':1,'B':2}
pd.DataFrame([my_dict])
A B
0 1 2
解决方案 3:
pd.DataFrame.from_records
当你手头已经有字典时,你也可以使用更方便的方法:
df = pd.DataFrame.from_records([{ 'A':a,'B':b }])
如果需要,您还可以通过以下方式设置索引:
df = pd.DataFrame.from_records([{ 'A':a,'B':b }], index='A')
解决方案 4:
首先,您需要创建一个 pandas 系列。第二步是将 pandas 系列转换为 pandas 数据框。
import pandas as pd
data = {'a': 1, 'b': 2}
pd.Series(data).to_frame()
您甚至可以提供列名。
pd.Series(data).to_frame('ColumnName')
解决方案 5:
也许 Series 可以提供您需要的所有功能:
pd.Series({'A':a,'B':b})
DataFrame 可以看作是 Series 的集合,因此你可以:
将多个系列连接成一个数据框(如此处所述)
将系列变量添加到现有数据框中(此处为示例)
解决方案 6:
熊猫魔法正在发挥作用。所有逻辑都失效了。
错误消息"ValueError: If using all scalar values, you must pass an index"
表明您必须传递索引。
这并不一定意味着传递索引会让 pandas 按照你的意愿去做
当你传递索引时,pandas 会将你的字典键视为列名,并将值视为索引中每个值应包含的列内容。
a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])
A B
1 2 3
传递更大的索引:
df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])
A B
1 2 3
2 2 3
3 2 3
4 2 3
如果没有指定索引,DataFrame 通常会自动生成索引。但是,Pandas 不知道您需要多少行2
。3
不过,您可以更明确地指定它
df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2
A B
0 2 3
1 2 3
2 2 3
3 2 3
但是默认索引是基于 0 的。
我建议在创建数据框时始终将列表字典传递给数据框构造函数。这样其他开发人员更容易阅读。Pandas 有很多注意事项,不要要求其他开发人员必须精通所有这些注意事项才能阅读您的代码。
解决方案 7:
我通常使用以下命令从字典中快速创建一个小表。
假设您有一个字典,其中的键是文件名,值为其对应的文件大小,您可以使用以下代码将其放入 DataFrame 中(注意字典上的 .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
解决方案 8:
您可以尝试:
df2 = pd.DataFrame.from_dict({'a':a,'b':b}, orient = 'index')
从“orient”参数的文档中可以看出:如果传递的字典的键应该是结果 DataFrame 的列,则传递“columns”(默认)。否则,如果键应该是行,则传递“index”。
解决方案 9:
您需要提供可迭代对象作为 Pandas DataFrame 列的值:
df2 = pd.DataFrame({'A':[a],'B':[b]})
解决方案 10:
我对 numpy 数组有同样的问题,解决方案是将它们展平:
data = {
'b': array1.flatten(),
'a': array2.flatten(),
}
df = pd.DataFrame(data)
解决方案 11:
要弄清楚“ValueError”,需要了解 DataFrame 和“标量值”。要从dict
创建 Dataframe ,至少需要一个数组。
在我看来,数组本身是索引的。
因此,如果存在类似数组的值,则无需指定索引。
例如,['a', 's', 'd', 'f'] 中每个元素的索引分别为 0,1,2,3。
df_array_like = pd.DataFrame({
'col' : 10086,
'col_2' : True,
'col_3' : "'at least one array'",
'col_4' : ['one array is arbitrary length', 'multi arrays should be the same length']})
print("df_array_like:
", df_array_like)
输出:
df_array_like:
col col_2 col_3 col_4
0 10086 True 'at least one array' one array is arbitrary length
1 10086 True 'at least one array' multi arrays should be the same length
如输出所示,DataFrame 的索引为 0 和 1。
恰好与数组的索引相同 ['一个数组是任意长度', '多个数组应该是相同的长度']
如果注释掉“col_4”,则会出现
ValueError(“如果使用所有标量值,则必须传递索引”)
导致标量值(整数、布尔值和字符串)没有索引
请注意,Index(...) 必须使用某种集合来调用,
因为用于定位 DataFrame
索引的所有行的索引应该是一个数组。例如
df_scalar_value = pd.DataFrame({
'col' : 10086,
'col_2' : True,
'col_3' : "'at least one array'"
}, index = ['fst_row','snd_row','third_row'])
print("df_scalar_value:
", df_scalar_value)
输出:
df_scalar_value:
col col_2 col_3
fst_row 10086 True 'at least one array'
snd_row 10086 True 'at least one array'
third_row 10086 True 'at least one array'
我是初学者,正在学习 Python 和英语。