如何根据 groupby 列表的多个值对数据帧进行子集化
How to subset a dataframe based on multiple values of groupby list
我有一个如下所示的数据框
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))
正如您在输入数据框中看到的那样,一些 ID 有多种颜色与之关联。
现在,我想创建一个 ID 为 Yellow
和 Green
的数据框子集
因此,我尝试了以下操作并获得了每个 ID 的颜色列表
fd.groupby('ID',as_index=False)['color'].aggregate(lambda x: list(x))
我想检查 groupby 列表中的 Yellow
和 Green
等值,然后对数据框进行子集化
我希望我的输出如下图所示(只有两个 ID 有黄色和绿色)
ID
1
1
8
8
更新
输入数据框如下所示
过滤颜色为黄色或绿色的行,然后将数据框分组到 ID
并使用 nunique
转换颜色以检查 ID
具有 2 种独特的颜色。
s = df[df['color'].isin(['Yellow', 'Green'])]
s.loc[s.groupby('ID')['color'].transform('nunique').eq(2), 'ID']
结果
0 1
2 1
14 8
15 8
Name: ID, dtype: int64
根据新要求更新,这里我假设df1
是在groupby
:
之后得到的输入数据帧
s = pd.DataFrame([*df1['color']])
df1[s.mask(~s.isin(['Yellow', 'Green'])).nunique(1).eq(2)]
结果:
ID color
0 1 [Yellow, Red, Green]
7 8 [Green, Yellow]
从您的输入数据框中,您可以使用:
colors = ['Yellow', 'Green']
out = df[df['color'].apply(lambda x: set(x).issuperset(colors))]
print(out)
# Output
ID color
0 1 [Yellow, Red, Green]
7 8 [Green, Yellow]
我有一个如下所示的数据框
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))
正如您在输入数据框中看到的那样,一些 ID 有多种颜色与之关联。
现在,我想创建一个 ID 为 Yellow
和 Green
因此,我尝试了以下操作并获得了每个 ID 的颜色列表
fd.groupby('ID',as_index=False)['color'].aggregate(lambda x: list(x))
我想检查 groupby 列表中的 Yellow
和 Green
等值,然后对数据框进行子集化
我希望我的输出如下图所示(只有两个 ID 有黄色和绿色)
ID
1
1
8
8
更新
输入数据框如下所示
过滤颜色为黄色或绿色的行,然后将数据框分组到 ID
并使用 nunique
转换颜色以检查 ID
具有 2 种独特的颜色。
s = df[df['color'].isin(['Yellow', 'Green'])]
s.loc[s.groupby('ID')['color'].transform('nunique').eq(2), 'ID']
结果
0 1
2 1
14 8
15 8
Name: ID, dtype: int64
根据新要求更新,这里我假设df1
是在groupby
:
s = pd.DataFrame([*df1['color']])
df1[s.mask(~s.isin(['Yellow', 'Green'])).nunique(1).eq(2)]
结果:
ID color
0 1 [Yellow, Red, Green]
7 8 [Green, Yellow]
从您的输入数据框中,您可以使用:
colors = ['Yellow', 'Green']
out = df[df['color'].apply(lambda x: set(x).issuperset(colors))]
print(out)
# Output
ID color
0 1 [Yellow, Red, Green]
7 8 [Green, Yellow]