[英]ValueError: setting an array element with a sequence. for Pandas
I have a Pandas dataframe called output
.我有一个名为
output
的 Pandas 数据框。 The basic issue is that I would like to set a certain row, column in the dataframe
to a list using the ix
function and am getting ValueError: setting an array element with a sequence.
基本问题是我想使用
ix
函数将dataframe
框中的某个行、列设置为一个列表,并且得到ValueError: setting an array element with a sequence.
My understanding is that a dataframe element was like a list element, it could hold anything (string, list, tuple, etc).我的理解是数据框元素就像一个列表元素,它可以容纳任何东西(字符串、列表、元组等)。 Am I not correct?
我不正确吗?
Basic setup:基本设置:
import pandas as pd
output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'])
print output.ix['Project1', 'Sold Count']
# -> 800
works fine:工作正常:
output.ix['Project1', 'Sold Count'] = 400.0
print output.ix['Project1', 'Sold Count']
# -> 400.0
doesn't work:不起作用:
output.ix['Project1', 'Sold Count'] = [400.0]
# -> ValueError: setting an array element with a sequence.
If you really want to set a list as the value for the element, the issue is with the dtype
of the column, when you create the DataFrame, the dtype gets inferred as float64
, since it only contains numeric values.如果您真的想将列表设置为元素的值,则问题出在列的
dtype
上,当您创建 DataFrame 时,dtype 被推断为float64
,因为它只包含数值。
Then when you try to set a list as the value, it errors out, due to the dtype
.然后,当您尝试将列表设置为值时,由于
dtype
,它会出错。 A way to fix this would be to use a non-numeric dtype (like object
) or so.解决此问题的一种方法是使用非数字 dtype (如
object
)左右。 Example -例子 -
output['Sold Count'] = output['Sold Count'].astype(object)
output.loc['Project1','Sold Count'] = [1000.0,800.0] #Your list
Demo -演示 -
In [91]: output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'])
In [92]: output
Out[92]:
Sold Count
Project1 800
In [93]: output['Sold Count'] = output['Sold Count'].astype(object)
In [94]: output.loc['Project1','Sold Count'] = [1000.0,800.0]
In [95]: output
Out[95]:
Sold Count
Project1 [1000.0, 800.0]
You can also specify the dtype
while creating the DataFrame, Example -您还可以在创建 DataFrame 时指定
dtype
,例如 -
output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'],dtype=object)
output.loc['Project1','Sold Count'] = [1000.0,800.0]
Demo -演示 -
In [96]: output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'],dtype=object)
In [97]: output.loc['Project1','Sold Count'] = [1000.0,800.0]
In [98]: output
Out[98]:
Sold Count
Project1 [1000.0, 800.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.