簡體   English   中英

將多個pandas數據幀列與另一個具有不同長度和索引的數據幀的一列進行比較

[英]compare multiple columns of pandas dataframe with one column of another dataframe having different length and index

我有數據幀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中添加一個列'Result',如果列'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

您可以通過比較DataFrame.lt通過位置選定列DataFrame.iloc或列名的列表,檢查是否所有True每行小號DataFrame.all和設定值numpy.where到新列:

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))

另一個想法是通過Series.gt與每個選定列的最大值進行比較,然后通過Series.mul進行多次Series.mul

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

您可以獲取每行的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM