2

Assuming that I have a dataframe with the following values:

id    product1sold   product2sold   product3sold
1     2              3              3
2     0              0              5
3     3              2              1

How do I add a 'most_sold' and 'least_sold' column containing all most and least sold products in a list per id? It should look like this.

id    product1   product2   product3    most_sold                least_sold
1        2          3          3        [product2, product3]      [product1]     
2        0          0          5        [product3]                [product1, product2]
3        3          2          1        [product1]                [product3]

2 Answers 2

2

Use list comprehension with test minimal and maximal values for list of products:

#select all columns without first
df1 = df.iloc[:, 1:]
cols = df1.columns.to_numpy()

df['most_sold'] = [cols[x].tolist() for x in df1.eq(df1.max(axis=1), axis=0).to_numpy()]
df['least_sold'] = [cols[x].tolist() for x in df1.eq(df1.min(axis=1), axis=0).to_numpy()]
print (df)
   id  product1sold  product2sold  product3sold                     most_sold  \
0   1             2             3             3  [product2sold, product3sold]   
1   2             0             0             5                [product3sold]   
2   3             3             2             1                [product1sold]   

                     least_sold  
0                [product1sold]  
1  [product1sold, product2sold]  
2                [product3sold]  

If performance is not important is possible use DataFrame.apply:

df1 = df.iloc[:, 1:]

f = lambda x: x.index[x].tolist()
df['most_sold'] = df1.eq(df1.max(axis=1), axis=0).apply(f, axis=1)
df['least_sold'] = df1.eq(df1.min(axis=1), axis=0).apply(f, axis=1)
Sign up to request clarification or add additional context in comments.

Comments

-1

You can do something like this.

minValueCol = yourDataFrame.idxmin(axis=1) maxValueCol = yourDataFrame.idxmax(axis=1)

Comments

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.