第一次重新创建示例:
import pandas as pd
data = [{"Year" : 2016, "ID" : 1, "Value" : 100},
{"Year" : 2017, "ID" : 1, "Value" : 102},
{"Year" : 2017, "ID" : 1, "Value" : 105},
{"Year" : 2018, "ID" : 1, "Value" : 98},
{"Year" : 2016, "ID" : 2, "Value" : 121},
{"Year" : 2016, "ID" : 2, "Value" : 101},
{"Year" : 2016, "ID" : 2, "Value" : 133},
{"Year" : 2018, "ID" : 3, "Value" : 102}]
df = pd.DataFrame(data)
并仔细查看汇总数据,看看是什么。
df.groupby("ID")['Year'].apply(list)
返回以下内容:
ID 1 [2016, 2017, 2017, 2018]
2 [2016, 2016, 2016]
3 [2018] Name: Year, dtype: object
所以 ID 1 出现在所有 4 年中,ID 2 出现了 3 次,但只出现在 2016 年,ID 3 只出现一次,在 2018 年这一年。
将聚合函数从 list 更改为 set 会返回稍微不同的视图:
df.groupby("ID")['Year'].apply(set)
ID
1 {2016, 2017, 2018}
2 {2016}
3 {2018}
Name: Year, dtype: object
这显示了 ID 1 如何分布在 3 年中,而 ID 2 和 3 分别仅分布在一年中。
如果您想测试给定 ID 是否仅与一年相关联,您可以保存并引用其中一个字典,测试所选年份返回的值。
unique_lookup_set = dict(df.groupby("ID")['Year'].apply(set))
def contains_and_only_contains(value, collection):
if value in collection and len(set(collection))==1:
return 1
else:
return 0
现在尝试用答案生成一个系列,进行测试:
df.apply(lambda x : contains_and_only_contains(2018, unique_lookup_set.get(x['ID'])), axis=1)
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
dtype: int
好,最后,将该系列包含到原始数据框中以获得最终输出。
df['ID_only_in_2018']=df.apply(lambda x : contains_and_only_contains(2018, unique_lookup_set.get(x['ID'])), axis=1)
df
|
Year |
ID |
Value |
ID_only_in_2018 |
| 0 |
2016 |
1 |
100 |
0 |
| 1 |
2017 |
1 |
102 |
0 |
| 2 |
2017 |
1 |
105 |
0 |
| 3 |
2018 |
1 |
98 |
0 |
| 4 |
2016 |
2 |
121 |
0 |
| 5 |
2016 |
2 |
101 |
0 |
| 6 |
2016 |
2 |
133 |
0 |
| 7 |
2018 |
3 |
102 |
1 |