Pandas If Else 条件对多列

时间:2021-07-24 02:35:30

标签: python pandas dataframe if-statement

我有一个 df 为:

df:
        col1       col2       col3        col4        col5
0       1.36       4.31       7.66           2           2
1       2.62       3.30       2.48           2           1
2       5.19       3.58       1.62           0           2
3       2.06       3.16       3.50           1           1
4       2.19       2.98       3.38           1           1

我想要

col6 在 (col4 > 1 and col5 > 1) else 0 时返回 1

col7 在 (col4 > 1 and col5 > 1 and col 4 + col5 > 2) else 0 时返回 1

我正在努力

df.loc[df['col4'] > 0, df['col5'] > 0, 'col6'] = '1'

但是我收到错误:

File "pandas\_libs\index.pyx", line 269, in pandas._libs.index.IndexEngine.get_indexer
  File "pandas\_libs\hashtable_class_helper.pxi", line 5247, in pandas._libs.hashtable.PyObjectHashTable.lookup
TypeError: unhashable type: 'Series'

如何执行此操作?

5 个答案:

答案 0 :(得分:3)

当您对 Series 对象或数组进行按位运算时,您会得到一个布尔数组,其中每个元素为 True 或 False。这些基本上是 0 或 1,实际上在大多数情况下更方便:

df['col6'] = (df['col4'] > 1) & (df['col5'] > 1)
df['col7'] = df['col6']

最后一个不是一个聪明的把戏。如果两个数都 >1,那么它们的和当然必须 >2。如果您绝对想要整数 0 和 1 而不是布尔值,请使用 Series.astype:

df['col6'] = ((df['col4'] > 1) & (df['col5'] > 1)).astype(int)

答案 1 :(得分:3)

我们可以做类似eval

df['col6'] = df.eval('col4 > 1 and col5 > 1').astype(int)
df['col7'] = df.eval('col4 > 1 and col5 > 1 and col4 + col5 > 2').astype(int)

答案 2 :(得分:2)

试试:

c1=df['col4'].gt(1) & df['col5'].gt(1)
#your 1st condition
c2=c1 & df['col4'].add(df['col5']).gt(2)
#your 2nd condition

最后:

df['col6']=c1.astype(int)
df['col7']=c2.astype(int)

通过 numpy 的 where() 方法:

c1=df['col4'].gt(1) & df['col5'].gt(1)
c2=c1 & df['col4'].add(df['col5']).gt(2)


df['col6']=np.where(c1,1,0)
df['col7']=np.where(c2,1,0)

答案 3 :(得分:2)

您可以简单地使用按位运算符:

df['col6'] = ((df["col4"]>1) & (df["col5"]>1))*1
df['col7'] = ((df["col4"]>1) & (df["col5"]>1) & (df['col4']+df['col5']>2))*1

>>> df
   col1  col2  col3  col4  col5  col6  col7
0  1.36  4.31  7.66     2     2     1     1
1  2.62  3.30  2.48     2     1     0     0
2  5.19  3.58  1.62     0     2     0     0
3  2.06  3.16  3.50     1     1     0     0
4  2.19  2.98  3.38     1     1     0     0

答案 4 :(得分:2)

创建一个变量来保存列:

columns = ['col4', 'col5']

条件 1:

cond1 = df.filter(columns).gt(1).all(1)

条件 2:

cond2 = df.filter(columns).sum(1).gt(2)

通过分配创建新列:

df.assign(col6 = cond1.astype(int), 
          col7 = (cond1 & cond2).astype(int)
          )


   col1  col2  col3  col4  col5  col6  col7
0  1.36  4.31  7.66     2     2     1     1
1  2.62  3.30  2.48     2     1     0     0
2  5.19  3.58  1.62     0     2     0     0
3  2.06  3.16  3.50     1     1     0     0
4  2.19  2.98  3.38     1     1     0     0
相关问题