python - 如何在 Pandas 中做一系列系列

标签 python pandas

假设我有两个系列:a 和 b,

a = Series(None, index=['a','b','c'])
b = Series('lol', index=['j','k','l'])

我想将 b 存储为 a 的元素之一,

a['a'] = b

但是我明白了

ValueError:使用序列设置数组元素。

是否可以将 Pandas 系列存储在 Pandas 系列中?我该怎么做?谢谢。

最佳答案

您可以使用 astype 方法重铸 dtype :

In [11]: a = a.astype(object)

In [12]: a['a'] = b

In [13]: a
Out[13]: 
a    [lol, lol, lol]
b                NaN
c                NaN

或者(使用astype)在构造a时你可以强制dtype为对象:

In [14]: a = Series(None, index=['a','b','c'], dtype=object)

出现此错误的原因是 float64 不允许 Series 并且同样不允许字符串 - 尝试设置 a ['a'] = 'lol' 并且您将得到一个 ValueError

In [21]: a = Series(None, index=['a','b','c'])

In [22]: a.dtype
Out[22]: dtype('float64')

您可以阅读有关 type-casting in the docs 的更多信息.

关于python - 如何在 Pandas 中做一系列系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14235487/

相关文章:

python - Git + Python Virtualenvs : unique directory across repositories

python - 旋转、缩放和平移二维坐标?

python - 如何将负位表示的数字转换为 python3 中的实际负 int 值?

python - 用于列表理解 Python 的多个条件语句

Python 正则表达式 : remove certain HTML tags and the contents in them

python - 在字典中存储 lambda

python - Pandas to_dict() 将日期时间转换为时间戳

python - 我们可以从 csv 文件中自动检测给定列的日期时间格式吗?

python - 'one-hot-encoded' 的 'feature Importance' 变量的显示名称

python - read_sql 和 redshift 在 unicode 上给出错误