Python 比较数据帧中行内的列值
我有一个具体的和一般的问题,我正试图解决 具体问题: 我想在数据帧中创建一个新列,如果列C1为8且行中的所有其他值小于8,则该列的值为1。如何在逻辑上同时对所有其他列求反?以下是我有缺陷尝试的代码:Python 比较数据帧中行内的列值,python,pandas,Python,Pandas,我有一个具体的和一般的问题,我正试图解决 具体问题: 我想在数据帧中创建一个新列,如果列C1为8且行中的所有其他值小于8,则该列的值为1。如何在逻辑上同时对所有其他列求反?以下是我有缺陷尝试的代码: df["C1is_8"] = df.apply(lambda row:(row['C1']==8)& ~(row['C1']<8) ,axis=1).astype(int) 一般问题:如何重写上述代码的某些版本,以便对其进行概括(即第[I]行),使其适用于任何列,而不仅仅是“C1”?
df["C1is_8"] = df.apply(lambda row:(row['C1']==8)& ~(row['C1']<8) ,axis=1).astype(int)
一般问题:如何重写上述代码的某些版本,以便对其进行概括(即第[I]行),使其适用于任何列,而不仅仅是“C1”?我认为这个答案满足您的具体问题和一般问题,使用
过滤器和所有:
# 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
#定义要应用第一个条件的列
col='C1'
#Python 3.6或更高版本,带有f字符串:
df['new_col']=((df[col]==8)和(df.filter(regex=f'[^{col}]')<8.all(1)).astype(int)
#否则:
df['new_col']=((df[col]==8)和(df.filter(regex='[^{}]'.format(col))<8.all(1)).astype(int)
>>>df
C1 C2 C3 C4新颜色
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
@sacul,请您解释一下all
,尽管我理解pandas.Series.all:如果所有元素都为True,则返回True
,我想当您说all(1)
时columns@pygo,没错,它检查一行中的所有值(除过滤掉的值外)(即跨所有列)满足<8
条件
# 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