Python 检查某些列';在Pandas中使用groupby时的值

Python 检查某些列';在Pandas中使用groupby时的值,python,pandas,dataframe,group-by,Python,Pandas,Dataframe,Group By,我有一个这样的数据帧 df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Bob', 'Joe', 'Joe', 'Joe'], 'ID': [1,2,3,4,5,6], 'Value': [1,1,1,0,0,1]}) df Name ID Value Bob 1 1 Bob 2 1 Bob

我有一个这样的数据帧

df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Bob', 'Joe', 'Joe', 'Joe'],
                'ID': [1,2,3,4,5,6],
                'Value': [1,1,1,0,0,1]})
df

 Name    ID    Value   
 Bob     1       1          
 Bob     2       1          
 Bob     3       1          
 Joe     4       0          
 Joe     5       0          
 Joe     6       1          
目标是计算
结果
列。这是通过检查
name
列中的每个组来完成的,在本例中为Bob&Joe

因此,对于每个组,如果
value
列中的值都是
1
,则该组的
result
列中的值都是1。如果值均为0,则该组的
结果
列值均为0。如果值是1和0的混合,则该组的
结果
列将全部为0

因此,输出应如下所示:

Name    ID    Value    Result
 Bob     1       1       1   
 Bob     2       1       1   
 Bob     3       1       1   
 Joe     4       0       0   
 Joe     5       0       0   
 Joe     6       1       0   
困难在于创建这些组,然后检查每个组

我的尝试:

df = df.groupby('Name')

df['Result'] = df.apply(lambda x: x['Value'])

all
groupby+transform一起使用

df['Result'] = df.groupby('Name')['Value'].transform('all').astype(int)
# or df['Result'] = df['Value'].eq(1).groupby(df['Name']).transform('all').astype(int)
print(df)

IIUC


如果值列中的值是另外两个值,例如“Y”和“N”,该怎么办?而不是1和0。@Muzz然后使用带注释的解决方案,
df['Result']=df['Value'].eq('Y').groupby(df['Name']).transform('all').astype(int)
,也可以使用replace-ro-replace
Y
替换为1和
N
替换为0,
df=df.replace({'Y':1,'N':0})
,但是我更喜欢第一个
  Name  ID  Value  Result
0  Bob   1      1       1
1  Bob   2      1       1
2  Bob   3      1       1
3  Joe   4      0       0
4  Joe   5      0       0
5  Joe   6      1       0
df['Result']=df.groupby('Name').Value.all().reindex(df.Name).astype(int).values
df
Out[57]: 
  Name  ID  Value  Result
0  Bob   1      1       1
1  Bob   2      1       1
2  Bob   3      1       1
3  Joe   4      0       0
4  Joe   5      0       0
5  Joe   6      1       0