Python 如何有条件地从系列中选择项目
我使用的是一个由数字列表组成的熊猫系列,以单词作为索引:Python 如何有条件地从系列中选择项目,python,list,pandas,conditional,list-comprehension,Python,List,Pandas,Conditional,List Comprehension,我使用的是一个由数字列表组成的熊猫系列,以单词作为索引: $10 [1, 0, 1, 1, 1, 1, 1] $100 [0, 0, 0] $15 [1] $19 [0, 0] $1? [1, 1] $20 [0,
$10 [1, 0, 1, 1, 1, 1, 1]
$100 [0, 0, 0]
$15 [1]
$19 [0, 0]
$1? [1, 1]
$20 [0, 1, 1]
$20-$40 [0]
我试图编写一些简单的代码,创建一个新的系列,其中只包括包含长度为“n”或更大列表的项目
有点像系列的列表理解
感谢您的帮助您应该避免在
系列
对象中使用列表
s,但您可以这样做:
编辑:用法
# DON'T use `eval` in production I'm just using it for convenience here
In [7]: s = read_clipboard(sep=r'\s{2,}', index_col=0, header=None, squeeze=1).map(eval)
In [8]: s
Out[8]:
0
$10 [1, 0, 1, 1, 1, 1, 1]
$100 [0, 0, 0]
$15 [1]
$19 [0, 0]
$1? [1, 1]
$20 [0, 1, 1]
$20-$40 [0]
In [20]: n = 3
In [21]: s.map(len) >= n
Out[21]:
0
$10 True
$100 True
$15 False
$19 False
$1? False
$20 True
$20-$40 False
Name: 1, dtype: bool
In [22]: s[s.map(len) >= n]
Out[22]:
0
$10 [1, 0, 1, 1, 1, 1, 1]
$100 [0, 0, 0]
$20 [0, 1, 1]
Name: 1, dtype: object
您不应该在系列
对象中使用列表
,因为它们是引擎盖下的对象
数组,而不是同质类型的系列
,它可以利用numpy
的速度
s[s.map(len) >= n]
谢谢实际上,我将它从列表字典转换为一个系列对象。为什么不使用系列更好?解决方案是否与列表词典相同?这并不是说使用
系列
是“不好的”,而是当你将任意对象放入系列
时,它们的速度要比使用同质类型的系列
慢得多。