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
195 views
in Technique[技术] by (71.8m points)

Comparison of DataFrame columns and adding two more columns to DataFrame, based on comparison in Python Pandas

I have a DataFrame like this:

 category    uid sales_1 sales_2
0    Grocery     1   XX   XX
1    Grocery     2   XX   ZZ
2    Sports      3   XX   ZZ
3    Grocery     4   ZZ   XX
4    Beauty      5   ZZ   ZZ
5    Beauty      6   ZZ   ZZ
6    Sports      7   ZZ   XX
7    Grocery     8   ZZ   XX
...

I need to compare sales_1 column with sales_2 column. The result of comparison would be reflected in 2 new columns first and second. If sales_1 == sales_2 then values in theese 2 new columns should be 'no changes' and 'OK'. If sales_1 != sales_2 the values should be 'changed' and 'gap'. In the end I would like to have a following DataFrame:

 category    uid sales_1 sales_2  first     second
0    Grocery     1   XX   XX    no changes  OK
1    Grocery     2   XX   ZZ    changed     gap
2    Sports      3   XX   ZZ    changed     gap
3    Grocery     4   ZZ   XX    changed     gap
4    Beauty      5   ZZ   ZZ    no changes  OK
5    Beauty      6   ZZ   ZZ    no changes  OK
6    Sports      7   ZZ   XX    changed     gap
7    Grocery     8   ZZ   XX    changed     gap
...

I would really appreciate any suggestion.

question from:https://stackoverflow.com/questions/65938106/comparison-of-dataframe-columns-and-adding-two-more-columns-to-dataframe-based

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

1 Reply

0 votes
by (71.8m points)

You can use the where() function from numpy:

df['first'] = np.where(df.sales_1 == df.sales_2, 'no changes', 'changed')
df['second'] = np.where(df.sales_1 == df.sales_2, 'OK', 'gap')

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

...