【问题标题】:How to conditionally select items from a pandas Series如何有条件地从熊猫系列中选择项目
【发布时间】:2013-08-19 22:42:24
【问题描述】:

我正在使用由数字列表组成的 Pandas 系列,以单词为索引:

$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”或更大的列表的项目。

有点像系列的列表理解。

感谢您的帮助

【问题讨论】:

    标签: python list pandas conditional list-comprehension


    【解决方案1】:

    您应该避免在Series 对象中使用lists,但您可以像这样执行您的要求:

    编辑:用法

    # 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
    

    您不应该在Series 对象中使用lists,因为它们实际上是object 数组,而不是同质类型的Series,后者可以利用numpy 的速度。

    【讨论】:

    • 谢谢!我实际上将它转换为列表字典中的系列对象。为什么最好不要使用系列?列表字典的解决方案是否相同?
    • 这并不是说使用 Series 是“坏的”,而是当你将任意对象放入 Series 时,它们比使用同质类型的 Series 时要慢得多。
    【解决方案2】:

    试试这个:

    s[s.map(len) >= n]
    

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      相关资源
      最近更新 更多