简体   繁体   English

在熊猫的元组列表中选择行

[英]selecting rows in a tuplelist in pandas

I have a list of tuples as below in python: 我在python中有如下的元组列表:

   Index        Value
     0         (1,2,3)
     1         (2,5,4)
     2         (3,3,3)

How can I select rows from this in which the second value is less than or equal 2? 如何从中选择第二个值小于或等于2的行?

EDIT: 编辑:

Basically, the data is in the form of [(1,2,3), (2,5,4), (3,3,3)....] 基本上,数据的格式为[(1,2,3), (2,5,4), (3,3,3)....]

You could slice the tuple by using apply : 您可以使用apply来切片tuple

df[df['Value'].apply(lambda x: x[1] <= 2)]

图片


Seems, it was a list of tuples and not a DF : 似乎是元组列表,而不是DF

To return a list back: 要返回list

data = [item for item in [(1,2,3), (2,5,4), (3,3,3)] if item[1] <= 2]
# [(1, 2, 3)]

To return a series instead: 要返回series

pd.Series(data)
#0    (1, 2, 3)
#dtype: object
df[df["Value"].str[1] <= 2]

您可以阅读以获取更多详细信息-http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str

just to put this out there. 只是为了把它放在那里。 you should read mcve . 您应该阅读mcve your question was/is confusing because it looks as though you've got 2 good answers and your not satisfied. 您的问题令人困惑,因为看起来您有2个不错的答案,但您不满意。 then you edited your question to be clearer, but just barely. 然后您将问题编辑得更清楚,但几乎没有。

ok, now that i've got my editorial out of the way. 好吧,现在我已经摆脱了我的社论。


setup 设定
this is what i'm assuming i'm working with 这就是我所假设的

# list of tuples
lot = [(1, 2, 3), (2, 5, 4), (3, 3, 3)]

desired output 期望的输出
i think. 我认为。 btw, nothing to do with pandas at all 顺便说一句,与熊猫完全无关

[(a, b, c) for a, b, c in lot if b <= 2]

[(1, 2, 3)]

with pandas 与熊猫
however, since you did tag this pandas 但是,因为您确实标记了这只大熊猫

s = pd.Series(lot)

@TrigonaMinima's answer, give them credit if this works for you. @TrigonaMinima的答案,如果这对您有用,请给他们功劳。

s[s.str[1].le(2)]

0    (1, 2, 3)
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM