首页 > 解决方案 > 比较 Pandas 数据框中一行中的列值

问题描述

我有一个要解决的具体问题和一般问题。

具体问题: 我想在数据框中创建一个新列,如果列 C1 为 8,并且该行中的所有其他值都小于 8,则该列给出 1。我如何在逻辑上同时否定所有其他列?这是我有缺陷的尝试的代码:

df["C1is_8"] = df.apply(lambda row:(row['C1']==8)& ~(row['C1']<8) ,axis=1).astype(int)

下面的代码为上面的代码生成数据帧。

dict = { 'C1':[4,3,0,0,2,3,4,5,8,8,8,8],
         'C2':[8,3,3,7,6,5,3,5,6,8,8,8],
         'C3':[2,3,6,4,5,0,0,4,6,7,8,8],
         'C4':[8,5,4,4,4,3,2,1,4,2,6,8]
       }
columns = ['C1','C2','C3','C4']
Index = [1,2,3,4,5,6,7,8,9,10,11,12]
df = pd.DataFrame(dict,index = Index,columns = columns)
df = OGdf[::-1]
df

一般问题:我如何重写上面代码的某个版本,以便我可以概括它(即 row[i] ),以便它可以应用于任何列,而不仅仅是'C1'?

标签: pythonpandas

解决方案


我认为这个答案可以满足您的具体问题和一般问题,使用filterand all

# define the column you want to apply your first condition to
col = 'C1'

# Python 3.6 or above, with f-strings:
df['new_col'] = ((df[col] == 8) & (df.filter(regex=f'[^{col}]') < 8).all(1)).astype(int)
# Otherwise:
df['new_col'] = ((df[col] == 8) & (df.filter(regex='[^{}]'.format(col)) < 8).all(1)).astype(int)

>>> df
    C1  C2  C3  C4  new_col
1    4   8   2   8        0
2    3   3   3   5        0
3    0   3   6   4        0
4    0   7   4   4        0
5    2   6   5   4        0
6    3   5   0   3        0
7    4   3   0   2        0
8    5   5   4   1        0
9    8   6   6   4        1
10   8   8   7   2        0
11   8   8   8   6        0
12   8   8   8   8        0

推荐阅读