如何在 pandas 中做一系列的系列 [英] How to do a series of series in pandas
问题描述
说我有两个系列:a和b,
Say I have two series: a and b,
a = Series(None, index=['a','b','c'])
b = Series('lol', index=['j','k','l'])
我想将b存储为a的元素之一,
I would like to store b as one of the elements of a,
a['a'] = b
但我明白了
ValueError: setting an array element with a sequence.
是否可以在熊猫系列中存储熊猫系列?我该怎么做?谢谢.
Is it possible to store a pandas series inside a pandas series? How can I do it? Thanks.
推荐答案
You can recast the dtype
using the method astype
:
In [11]: a = a.astype(object)
In [12]: a['a'] = b
In [13]: a
Out[13]:
a [lol, lol, lol]
b NaN
c NaN
构造a
时(或者使用astype
),可以强制dtype
成为对象:
Alternatively (to using astype
) when contructing a
you can force the dtype
to be object:
In [14]: a = Series(None, index=['a','b','c'], dtype=object)
出现此错误的原因是因为float64
不允许Series
,并且同样不允许字符串-尝试设置a['a'] = 'lol'
会得到ValueError
. /p>
The reason you are getting this error is because float64
, doesn't allow a Series
and similarly it doesn't allow strings - try to set a['a'] = 'lol'
and you'll get a ValueError
.
In [21]: a = Series(None, index=['a','b','c'])
In [22]: a.dtype
Out[22]: dtype('float64')
您可以在文档中阅读有关类型转换的更多信息.
这篇关于如何在 pandas 中做一系列的系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!