问题:
尝试使用标量构造 DataFrame 时变量中的值时,会遇到以下错误:
ValueError: If using all scalar values, you must pass an index
当使用所有值都是标量的字典初始化 DataFrame 时,会发生这种情况,如下例所示:
<code class="python">a = 2 b = 3 df2 = pd.DataFrame({'A': a, 'B': b})</code>
解决方案:
要解决此问题,有两个选项:
不要对列使用标量值,而是使用列表:
<code class="python">df = pd.DataFrame({'A': [a], 'B': [b]})</code>
如果必须使用标量值,请随字典一起传递索引:
<code class="python">df = pd.DataFrame({'A': a, 'B': b}, index=[0])</code>
这为 DataFrame 提供了理解数据结构所需的上下文。
示例:
以下代码演示了使用标量值构造 DataFrame 的正确方法:
<code class="python">a = 2 b = 3 df = pd.DataFrame({'A': [a], 'B': [b]}, index=[0]) print(df)</code>
输出:
A B 0 2 3
以上是以下是一些适合问答格式、英文且准确反映文章内容的标题选项: * **使用标量构建数据帧:为什么 \"ValueError\&qu的详细内容。更多信息请关注PHP中文网其他相关文章!