首页 > 解决方案 > 如何编写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]} 

标签: pythonpandasdata-cleaning

解决方案


首先比较所有值 by DataFrame.eq,然后测试每行是否至少有一个值是TruebyDataFrame.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)

推荐阅读