簡體   English   中英

如何根據相鄰列中的值將 lambda function 應用於特定列

[英]How to apply lambda function to specific column based on the values in the adjacent column

我正在嘗試將 lambda function 應用於 pandas 數據幀。 我的問題是如何使用 if 語句根據 b 列中的值將 lambda function 應用到 a 列。

A B C
2 5 7
4 5 9
6 7 9
df['B'].apply(lambda x: x+3 if x<(#the value in column C) else x)

您需要在 dataframe axis=1調用apply ,使用 axis=1 而不是B列:

>>> df.apply(lambda x: x['B']+3 if x['B']<x['C'] else x['B'], axis=1)
0     8
1     8
2    10
dtype: int64

但是,有效(更快)的方法是這樣做:

>>> df['B'] + df['B'].lt(df['C']) * 3
0     8
1     8
2    10
dtype: int64

暫無
暫無

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

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