python - 当值为 `pandas.Series.str` 时 `list` 如何工作?

标签 python pandas series

这是如何运作的?如果它将每个项目转换为字符串,我应该得到第一个字符,如 "[1,2]"[0] ----> '[' 但它被视为列表,如何?

>>> df = pd.DataFrame({'a':[[1,2],[2,3]]})
>>> df.a.str[0]
0    1
1    2
Name: a, dtype: int64

最佳答案

它有效,因为 stringlist 是可迭代的。这意味着 .str[0] 返回字符串的第一个值、列表的第一个值、可迭代的第一个值。

什么是可迭代:

正如Raymond Hettinger所述:

An ITERABLE is:

  • anything that can be looped over (i.e. you can loop over a string or file) or
  • anything that can appear on the right-side of a for-loop: for x in iterable: ... or
  • anything you can call with iter() that will return an ITERATOR: iter(obj) or
  • an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method suitable for indexed lookup.

关于python - 当值为 `pandas.Series.str` 时 `list` 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62078969/

相关文章:

python - 瓶颈给我错误的形状

python - Pandas 类型错误: unhashable type: 'slice'

python - 如何让 Pandas 创建新工作表而不是覆盖?

python - 如何去除日期、小时和秒的 Pandas 日期时间

python - orderedDict vs pandas 系列

python - Pandas :获取系列对象中的值(value)标签

python - 如何在Python中按工作日、月份等对pandas系列时间码进行排序/分组?

python - Keras减肥

python - 使用 numpy 'module' 对象没有属性 'array'

python - 在本地主机上运行 python 脚本