Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

python - Apply an operation on the value of column B depending on the value of column A - Pandas

I have the following dataset:

id  Wages   PayFreq
0   1013    Weekly
1   5000    Monthly
2   892     Weekly
3   2320    Bi-Weekly
4   1068    Weekly

I intend to perform the following operation:

if PayFreq == 'Monthly':
   (Wages / 4) * 52
elif PayFreq == 'Bi-Weekly':
   (Wages / 2) * 52
else:
    Wages * 52

I need to select the operation to apply to the wages column based on what is present in the PayFreq column. Any ideas ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would sugest to use Dataframe's apply as it is very simple and intuitive.

You can define a method you want to apply on the dataframe, you can choose either Lambda expression or explicit function for that. For example, here is a simple implementation with a function:

def func(row):
    if row['PayFreq'] == 'Monthly':
        return (row['Wages'] / 4) * 52
    elif row['PayFreq'] == 'Bi-Weekly':
        return (row['Wages'] / 2) * 52
    else:
        return row['Wages'] * 52

And in order to apply it on your dataframe (on the right axis):

df['NewWages'] = df.apply(func, axis=1)

The result:

   Wages    PayFreq  NewWages
0   1013     Weekly   52676.0
1   5000    Monthly   65000.0
2    892     Weekly   46384.0
3   2320  Bi-Weekly   60320.0
4   1068     Weekly   55536.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...