[英]Get last row with specific value in column, Python
I have我有
df = pd.DataFrame('data', car, 'ok') df = pd.DataFrame('data', car, 'ok')
df: df:
data car ok
2020-03-25 A
2020-04-01 A x
2020-04-15 A
2020-05-08 A x
2020-06-25 A x
2020-06-27 A
2020-07-15
I want to select last (old in this case) row being column 'ok' with "x"我想选择最后一行(在这种情况下为旧)行是“确定”列,并带有“x”
I want to obtain我想获得
2020-04-01 A x
Thanks!谢谢!
The head()
method on DataFrame
can give you the first n
rows of a DataFrame
.该head()
的方法, DataFrame
可以给你的第一n
一个行DataFrame
。 Indexing of a DataFrame will allow you to select rows meeting your filter criteria - to narrow to a subset DataFrame
with such rows. DataFrame 的索引将允许您选择符合过滤条件的行 - 缩小到具有此类行的DataFrame
子集。 Together, you could use them to do:您可以一起使用它们来执行以下操作:
r = df.loc[df.ok == 'x', :].head(1)
What you are doing here is narrowing to a subset DataFrame
where ok
is 'x'
(the df.loc[df.ok == 'x', :]
part), then taking the first row of it (the .head(1)
part).您在这里所做的是缩小到一个子集DataFrame
,其中ok
是'x'
( df.loc[df.ok == 'x', :]
部分),然后取它的第一行( .head(1)
部分)。 This of course assumes the DataFrame
is sorted by date as it is above.这当然假设DataFrame
按日期排序,如上所示。
Indexing is a huge and fundamental topic (think of it as the SQL WHERE
of pandas) so you should spend time gaining a deep knowledge of it.索引是一个庞大而基础的主题(将其视为WHERE
的 SQL WHERE
),因此您应该花时间深入了解它。 Here is a great tutorial .这是一个很棒的教程。 This one and this one are also good. 这个和这个也不错。
当您的数据未排序时,这也将起作用:
df[df.ok == 'x'][df.data == df.data.min()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.