find Item wise max sales on which month in python series?

Viewed 613
s1=pd.Series([100,200,300,400,500],index=['item1','item2','item3','item4','item5'])
s2=pd.Series([102,205,333,433,502],index=['item1','item2','item3','item4','item5'])
s3=pd.Series([101,2200,300,400,500],index=['item1','item2','item3','item4','item5'])
s4=pd.Series([102,2200,300,400,500],index=['item1','item2','item3','item4','item5'])
s5=pd.Series([104,2300,300,400,500],index=['item1','item2','item3','item4','item5'])
s6=pd.Series([105,2700,300,400,500],index=['item1','item2','item3','item4','item5'])
s7=pd.Series([105,2800,300,400,500],index=['item1','item2','item3','item4','item5'])
s8=pd.Series([306,2900,3900,400,500],index=['item1','item2','item3','item4','item5'])
s9=pd.Series([400,2090,300,400,500],index=['item1','item2','item3','item4','item5'])
s10=pd.Series([500,2900,3090,400,500],index=['item1','item2','item3','item4','item5'])
s11=pd.Series([600,2090,3090,400,500],index=['item1','item2','item3','item4','item5'])
s12=pd.Series([1000,200,300,400,500],index=['item1','item2','item3','item4','item5'])

these are sales data of item1, item2, item3, item4 and item5 for each month wise means s1 data is for month 1, s2 data is for month 2 so on. i need to find in which month item1 sold max , then item2, item3, item4, item5 through python programming.

i was trying like this , just checking if i am getting the values or not

def fn():
    for i in range(12):
        print(i)
print("Maximum Sales for Individual Items")
for i in s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12:
    for j in range(5):
        x=i[j]
        fn(x)
1 Answers

Organize this into a single DataFrame, where the row Index is the item and the column Index indicates the month. Then you can use .idxmax(axis=1) to get the month of maximum sales per item.

df = pd.concat([s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12], keys=range(1,13), axis=1)
df.idxmax(1)

#item1    12
#item2     8
#item3     8
#item4     2
#item5     2
#dtype: int64

If you want to know all months in the case of ties, find the max per item and use where + stack to keep only values that equal that max. This also retains the maximum value if that's important.

df.where(df.eq(df.max(axis=1), axis=0)).stack()

#item1  12    1000.0
#item2  8     2900.0
#       10    2900.0
#item3  8     3900.0
#item4  2      433.0
#item5  2      502.0
#dtype: float64
Related