[英]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.