我刚开始使用 python 和 pandas。我已经在 google 和 stack overflow 上搜索了我的问题的答案,但没能找到。 这是我需要做的:
我有一个 df,每个人 (id) 有几个数据行和一个名为 response_go 的变量,它可以编码为 1 或 0(类型 int64),例如这个(更大,每个人有 480 行... )
ID response_go
0 1 1
1 1 0
2 1 0
3 1 1
4 2 1
5 2 0
6 2 1
7 2 1
现在,我想为每个 ID/人检查 response_go 中的条目分别是全部编码为 0、全部编码为 1,还是两者都不是(else 条件)。到目前为止,我想出了这个:
ids = df['ID'].unique()
for id in ids:
if (df.response_go.all() == 1):
print "ID:",id,": 100% Go"
elif (df.response_go.all() == 0):
print "ID:",id,": 100% NoGo"
else:
print "ID:",id,": Mixed Response Pattern"
但是,它给了我以下输出:
ID: 1 : 100% NoGo
ID: 2 : 100% NoGo
ID: 2 : Mixed Response Pattern
应该是什么时候(因为包括 1 和 0)
ID: 1 : Mixed Response Pattern
ID: 2 : Mixed Response Pattern
如果之前有人问过这个问题,我真的很抱歉,但是在寻找答案时,我真的找不到解决这个问题的方法。如果之前已经回答过这个问题,请指出解决方案。谢谢大家!!!!真的很感激!
请您参考如下方法:
示例(具有不同的数据)-
df = pd.DataFrame({'ID' : [1] * 3 + [2] * 3 + [3] * 3,
'response_go' : [0, 0, 0, 1, 1, 1, 0, 1, 0]})
df
ID response_go
0 1 0
1 1 0
2 1 0
3 2 1
4 2 1
5 2 1
6 3 0
7 3 1
8 3 0
使用groupby + mean -
v = df.groupby('ID').response_go.mean()
v
ID
1 0.000000
2 1.000000
3 0.333333
Name: response_go, dtype: float64
使用 np.select 根据 response_go 的平均值计算您的状态 -
u = np.select([v == 1, v == 0, v < 1], ['100% Go', '100% NoGo', 'Mixed Response Pattern'])
或者,使用嵌套的 np.where 做同样的事情(稍微快一点)-
u = np.where(v == 1, '100% Go', np.where(v == 0, '100% NoGo', 'Mixed Response Pattern'))
现在,将结果返回 -
v[:] = u
v
ID
1 100% NoGo
2 100% Go
3 Mixed Response Pattern
Name: response_go, dtype: object
