将 Pandas 列中的值组合在一起,然后过滤另一列中的值
Group values together in Pandas column, then filter values in another column
Pandas 数据框看起来像这样:
Col1 Col2
A 1
A 1
A 1
B 0
B 0
B 1
B 1
B 1
C 1
C 1
C 1
C 1
我想在 Col1
中将所有内容组合在一起,然后检查 Col2
以查看该组的 all 值是否为 1。在此例如,所需的输出将是:
[A, C]
(因为只有 A 和 C 的值都设置为 1)。我该怎么做呢?
你的情况 groupby
和 all
df.groupby('Col1').Col2.all().loc[lambda x : x ].index.tolist()
Out[350]: ['A', 'C']
或没有 groupby
df.loc[~df.Col1.isin(df.Col1[df.Col2.eq(0)]),'Col1'].unique()
Out[352]: array(['A', 'C'], dtype=object)
来自评论
cs95:df.loc[df['Col2'].astype(bool).groupby(df['Col1']).transform('all'), 'Col1'].unique()
我们可以使用 all
和 groupby
:
out = df.Col2.groupby(df.Col1).all()
out.index[out].tolist()
# ['A', 'C']
理解
[k for k, d in df.Col2.eq(1).groupby(df.Col1) if d.all()]
['A', 'C']
Pandas 数据框看起来像这样:
Col1 Col2
A 1
A 1
A 1
B 0
B 0
B 1
B 1
B 1
C 1
C 1
C 1
C 1
我想在 Col1
中将所有内容组合在一起,然后检查 Col2
以查看该组的 all 值是否为 1。在此例如,所需的输出将是:
[A, C]
(因为只有 A 和 C 的值都设置为 1)。我该怎么做呢?
你的情况 groupby
和 all
df.groupby('Col1').Col2.all().loc[lambda x : x ].index.tolist()
Out[350]: ['A', 'C']
或没有 groupby
df.loc[~df.Col1.isin(df.Col1[df.Col2.eq(0)]),'Col1'].unique()
Out[352]: array(['A', 'C'], dtype=object)
来自评论
cs95:df.loc[df['Col2'].astype(bool).groupby(df['Col1']).transform('all'), 'Col1'].unique()
我们可以使用 all
和 groupby
:
out = df.Col2.groupby(df.Col1).all()
out.index[out].tolist()
# ['A', 'C']
理解
[k for k, d in df.Col2.eq(1).groupby(df.Col1) if d.all()]
['A', 'C']