Pandas Equivalent of R's which()

前端 未结 6 1630
广开言路
广开言路 2020-12-31 04:12

Variations of this question have been asked before, I\'m still having trouble understanding how to actually slice a python series/pandas dataframe based on conditions that

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 05:01

    enumerate() returns an iterator that yields an (index, item) tuple in each iteration, so you can't (and don't need to) call .index() again.

    Furthermore, your list comprehension syntax is wrong:

    indexfuture = [(index, x) for (index, x) in enumerate(df['colname']) if x > yesterday]
    

    Test case:

    >>> [(index, x) for (index, x) in enumerate("abcdef") if x > "c"]
    [(3, 'd'), (4, 'e'), (5, 'f')]
    

    Of course, you don't need to unpack the tuple:

    >>> [tup for tup in enumerate("abcdef") if tup[1] > "c"]
    [(3, 'd'), (4, 'e'), (5, 'f')]
    

    unless you're only interested in the indices, in which case you could do something like

    >>> [index for (index, x) in enumerate("abcdef") if x > "c"]
    [3, 4, 5]
    

提交回复
热议问题