Search code examples
pythonpandasplottrend

how can add trend arrow in python pandas?


I have a pandas's dataframe that contains some team and thir score in the years. the data is like this:

df = pd.DataFrame({'Team': ['A', 'B', 'C', 'D'],
              '2016' : [16, 13, 15, 19],
              '2017' : [15, 16, 14, 19],
              '2018' : [13, 17, 14, 17],
              '2019' : [15, 15, 16, 19]
             })

i want calculate rank of each team in each year and then track the change of ranking in each year for teams. i want show the change in rank with up and down arrow in pandas.

the result must be like this: result in excel


Solution

  • You can use df.rank with df.diff() on axis=1 , then use np.select with conditions and unicodes

    m = df.set_index('Team') #set Team as index
    n = m.rank(ascending=False,method='min').add_suffix('_rank') #get rank
    a = n.diff(axis=1).iloc[:,1:].add_suffix('_trned') #take difference on axis=1
    a[:] = np.select([a.lt(0),a.gt(0),a.eq(0)],[u"\u2193",u"\u2191",u"\u2192"])
    

    final = pd.concat((m,n,a),axis=1).reset_index()
    
      Team  2016  2017  2018  2019  2016_rank  2017_rank  2018_rank  2019_rank  \
    0    A    16    15    13    15        2.0        3.0        4.0        3.0   
    1    B    13    16    17    15        4.0        2.0        1.0        3.0   
    2    C    15    14    14    16        3.0        4.0        3.0        2.0   
    3    D    19    19    17    19        1.0        1.0        1.0        1.0   
    
      2017_rank_trned 2018_rank_trned 2019_rank_trned  
    0               ↑               ↑               ↓  
    1               ↓               ↓               ↑  
    2               ↑               ↓               ↓  
    3               →               →               →