[英]In Pandas, how can I filter all rows for a unique ID based on a condition affecting only certain entries?
I am working with a dataframe like this:我正在使用这样的 dataframe:
import pandas as pd
import datetime
records = [{'Name':'John', 'Start':'2020-01-01','Stop':'2020-03-31'}, {'Name':'John', 'Start':'2020-04-01','Stop':'2020-12-31'},
{'Name':'Mary', 'Start':'2020-01-01','Stop':'2020-03-15'}, {'Name':'Mary', 'Start':'2020-03-16','Stop':'2020-03-31'},
{'Name':'Mary', 'Start':'2020-04-01','Stop':'2020-12-31'}, {'Name':'Stan', 'Start':'2020-02-01','Stop':'2020-03-31'},
{'Name':'Stan', 'Start':'2020-04-01','Stop':'2020-12-31'}]
df = pd.DataFrame(records)
df['Start'] = pd.to_datetime(df['Start'])
df['Stop'] = pd.to_datetime(df['Stop'])
df
which gives the output这给出了 output
Name Start Stop
0 John 2020-01-01 2020-03-31
1 John 2020-04-01 2020-12-31
2 Mary 2020-01-01 2020-03-15
3 Mary 2020-03-16 2020-03-31
4 Mary 2020-04-01 2020-12-31
5 Stan 2020-02-01 2020-03-31
6 Stan 2020-04-01 2020-12-31
What I want to do is select all the records for all the individuals who have a start date of 2020-01-01.我想做的是 select 所有开始日期为 2020-01-01 的个人的所有记录。 That is, if someone doesn't have a record beginning on 1/1, then I don't want any of their records.
也就是说,如果某人没有从 1/1 开始的记录,那么我不想要他们的任何记录。 The results should give me this:
结果应该给我这个:
Name Start Stop
0 John 2020-01-01 2020-03-31
1 John 2020-04-01 2020-12-31
2 Mary 2020-01-01 2020-03-15
3 Mary 2020-03-16 2020-03-31
4 Mary 2020-04-01 2020-12-31
There should be no records for Stan in the output, because none of his entries start with 2020-01-01. output 中应该没有 Stan 的记录,因为他的条目都没有以 2020-01-01 开头。 Any ideas on how to accomplish this?
关于如何做到这一点的任何想法? Thanks!
谢谢!
Try the condition grouped by transform:尝试按变换分组的条件:
df[df['Start'].eq("2020-01-01").groupby(df["Name"]).transform('any')]
Name Start Stop
0 John 2020-01-01 2020-03-31
1 John 2020-04-01 2020-12-31
2 Mary 2020-01-01 2020-03-15
3 Mary 2020-03-16 2020-03-31
4 Mary 2020-04-01 2020-12-31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.