我有一个像下面这样的dataframe
ID,color
1, Yellow
1, Red
1, Green
2, Red
2, np.nan
3, Green
3, Red
3, Green
4, Yellow
4, Red
5, Green
5, np.nan
6, Red
7, Red
8, Green
8, Yellow
fd = pd.read_clipboard(sep=',')
fd = fd.groupby('ID',as_index=False)['color'].aggregate(lambda x: list(x))
正如您在输入dataframe中看到的,一些ID具有与它们关联的多种颜色。
现在,我想用ID创建一个子集dataframe,同时具有Yellow
和Green
所以,我尝试了下面的方法,并得到了每个ID的颜色列表
fd.groupby('ID',as_index=False)['color'].aggregate(lambda x: list(x))
我想检查groupby列表中的Yellow
和Green
等值,然后将dataframe子集
我期望我的输出如下所示(只有两个Id有黄色和绿色在一起)
ID
1
1
8
8
更新
输入dataframe如下所示
<img alt="在这里输入图像描述"src="https://i.stack.imgur.com/dXI0Q.png缧/>
从您的输入dataframe,您可以使用: