比较多列熊猫数据帧与另一列具有不同长度和索引的数据帧

时间:2019-05-11 10:57:29

标签: python pandas dataframe

我有数据框 dd1:

     A   B   C  D    E  
  0  V  10   5  18  20       
  1  W   9  18  11  13      
  2  X   8   7  12   5      
  3  Y   7   9   7   8       
  4  Z   6   5   3  90       

我想在dd1中添加一列“结果”,如果“ E”列中的值大于dd1列A,B,C和D中的值,则该列应返回零,否则返回大于dd1列E的值

   A   B   C   D   E  Result
0  V  10   5  18  20       0
1  W   9  18  11  13      18
2  X   8   7  12   5      12
3  Y   7   9   7   8       9
4  Z   6   5   3  90       0

2 个答案:

答案 0 :(得分:3)

您可以按DataFrame.lt位置选择的DataFrame.iloc列或列名列表进行比较,按DataFrame.all检查每行是否所有True,并按{ {3}}到新列:

df1 = df.iloc[:, 1:-1]
#for select by columns names
#df1 = df[['B','C','D']]
df['Result'] = np.where(df1.lt(df['E'], axis=0).all(axis=1), 0, df1.max(axis=1))

另一个想法是将numpy.where与选定列的最大值进行比较,然后将其乘以Series.gt

s = df.iloc[:, 1:-1].max(axis=1)
df['Result'] = s.gt(df['E']).mul(s)
print (df)
   A   B   C   D   E  Result
0  V  10   5  18  20       0
1  W   9  18  11  13      18
2  X   8   7  12   5      12
3  Y   7   9   7   8       9
4  Z   6   5   3  90       0

答案 1 :(得分:0)

您可以获得每行的max值(轴= 1),并将其与E列进行比较。如果此条件为True,则返回0,否则返回该行的max值:

df['Result'] = np.where(df.iloc[:, 1:].max(axis=1).eq(df['E']), # our condition
                        0,                                      # value if true
                        df.iloc[:, 1:].max(axis=1))             # value if false


print(df)
   A   B   C   D   E  Result
0  V  10   5  18  20       0
1  W   9  18  11  13      18
2  X   8   7  12   5      12
3  Y   7   9   7   8       9
4  Z   6   5   3  90       0

说明
numpy.where的工作方式如下:

np.where(condition, value if true, value if false)
相关问题