python - 如何编写for循环来查找Python中每一行的多列中存在或不存在的特定数字?
问题描述
我有一个这样的数据框:
abc = {'p1':[1,2,3,4,5,6,7,8,9,1],
'p2':[2,3,4,5,6,7,8,9,1,2],
'p3':[3,4,5,6,7,8,9,1,2,3]}
我想添加另一列来查找这 3 列中的每一行是否存在数字 1,如下所示:
我试过这个除了错误什么都没有。此处 1 = 是,0 = 否
is_1st_exist = []
for p in abc['p1'],abc['p2'],abc['p3']:
if (p[0] | p[1] | p[2] == 1)
is_1st_exist.append(1)
else is_1st_exist.append(0)
我应该怎么做才能低于 is_1st_exist 列?
abc = {'p1':[1,2,3,4,5,6,7,8,9,1],
'p2':[2,3,4,5,6,7,8,9,1,2],
'p3':[3,4,5,6,7,8,9,1,2,3],
'is_1st_exist?':[1,0,0,0,0,0,0,1,1,1]}
解决方案
首先比较所有值 by DataFrame.eq
,然后测试每行是否至少有一个值是True
byDataFrame.any
并最后转换为整数:
df = pd.DataFrame(abc)
df['is_1st_exist?'] = df.eq(1).any(axis=1).astype(int)
#alternative
#df['is_1st_exist?'] = np.where(df.eq(1).any(axis=1), 1, 0)
print (df)
p1 p2 p3 is_1st_exist?
0 1 2 3 1
1 2 3 4 0
2 3 4 5 0
3 4 5 6 0
4 5 6 7 0
5 6 7 8 0
6 7 8 9 0
7 8 9 1 1
8 9 1 2 1
9 1 2 3 1
如果要指定测试列list
:
cols = ['p1','p2','p3']
df['is_1st_exist?'] = df[cols].eq(1).any(axis=1).astype(int)
推荐阅读
- android - 透明覆盖在画布上绘图后失去透明度
- python - 在使用 Kmeans 之前是否需要从 MNIST 中提取特征向量
- templates - DotNet 模板:如何在不重复的情况下排除目录?
- javascript - 一步一步如何在 Rails 项目中包含 selectize.JS 构建 Ajax 请求和 Json 答案?
- regex - 使用正则表达式匹配不以 's 结尾的字符串
- angular - 错误:位置 652 处 JSON 中的意外标记]
- reactjs - 如何防止 Header 在登录屏幕上呈现?
- visual-studio - Visual Studio - 团队基础
- asp.net - 我无法创建 Azure 后端模板 VS 2019
- mysql - 分布式爬虫和一致性