从变量中的值构造 Pandas DataFrame 给出“ValueError:如果使用所有标量值,则必须传递索引"; [英] Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

查看:44
本文介绍了从变量中的值构造 Pandas DataFrame 给出“ValueError:如果使用所有标量值,则必须传递索引";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我不知道如何做到这一点.假设我有两个变量,如下所示.

a = 2乙 = 3

我想从中构建一个 DataFrame:

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

这会产生一个错误:

<块引用>

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

我也试过这个:

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

这给出了相同的错误信息.

解决方案

该错误消息说,如果您要传递标量值,则必须传递一个索引.因此,您不能对列使用标量值 - 例如使用列表:

<预><代码>>>>df = pd.DataFrame({'A': [a], 'B': [b]})>>>df甲乙0 2 3

或使用标量值并传递索引:

<预><代码>>>>df = pd.DataFrame({'A': a, 'B': b}, index=[0])>>>df甲乙0 2 3

This may be a simple question, but I can not figure out how to do this. Lets say that I have two variables as follows.

a = 2
b = 3

I want to construct a DataFrame from this:

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

This generates an error:

ValueError: If using all scalar values, you must pass an index

I tried this also:

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

This gives the same error message.

解决方案

The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:

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

or use scalar values and pass an index:

>>> df = pd.DataFrame({'A': a, 'B': b}, index=[0])
>>> df
   A  B
0  2  3

这篇关于从变量中的值构造 Pandas DataFrame 给出“ValueError:如果使用所有标量值,则必须传递索引";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆