1

I have a data frame like this:

Product_ID Store_1_qty Store_2_qty Store_3_qty
A          10          20          10
B          10          10          10
C          10          10          20

I want to add one more column which says 'true' or 'false' if column Store_2_qty, Store_3_qty are both equal to Store_1_qty. However sometimes extra columns like Store_4_qty, Store_5_qty are added, for which again I need to compare all columns to Store_1_qty

I tried this, but it is returning all False in last column

result['match'] = np.where(result.iloc[:, 1] == result.iloc[:, :1].all(1), 'True', 'False')

3 Answers 3

2

If Product_ID is column use DataFrame.eq, also you can compare all columns with first Store column:

result['match'] = (result.iloc[:, 1:].eq(result.iloc[:, 1], axis=0)).all(1) 
Sign up to request clarification or add additional context in comments.

1 Comment

result['match'] = (result.iloc[:, 1:].eq(result.iloc[:, 1], axis=0)).all(1) Worked for me. Many thanks.
0

If I understand it correctly all you need to do is test for uniqueness of you df entries:

# Assuming Product_ID is NOT your index:
df['match'] = df.iloc[:,2:].nunique(axis=1) == 1

# If Product_ID is your index it simplifies to:
df['match'] = df.nunique(axis=1) == 1

Result:

  Product_ID  Store_1_qty  Store_2_qty  Store_3_qty  match
0          A           10           20           10  False
1          B           10           10           10   True
2          C           10           10           20  False

Comments

0

Just an attempt. @jezrael's solution is better

df['match'] = df[['Store_2_qty', 'Store_3_qty']].eq(df['Store_1_qty'],axis=0).all(1)

Output:

  Product_ID  Store_1_qty  Store_2_qty  Store_3_qty  match
0          A           10           20           10  False
1          B           10           10           10   True
2          C           10           10           20  False

2 Comments

Actually in my case other columns like store_4_qty, 5, 6 etc can get added depending on data, that's why i needed something that could compare all columns, without me needing to edit the code.
Completely understood. That's why I mentioned @jezrael's solution is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.