这是如何运作的?如果它将每个项目转换为字符串,我应该得到第一个字符,如 "[1,2]"[0]
----> '['
但它被视为列表
,如何?
>>> df = pd.DataFrame({'a':[[1,2],[2,3]]})
>>> df.a.str[0]
0 1
1 2
Name: a, dtype: int64
最佳答案
它有效,因为 string
和 list
是可迭代的。这意味着 .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/