如何在 python pandas 中添加趋势箭头?
how can add trend arrow in python pandas?
我有一个 pandas 的数据框,其中包含多年来的一些球队和他们的得分。数据是这样的:
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]
})
我想计算每个球队每年的排名,然后跟踪球队每年排名的变化。
我想在 pandas.
中用向上和向下箭头显示排名变化
结果一定是这样的:
您可以使用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 → → →
我有一个 pandas 的数据框,其中包含多年来的一些球队和他们的得分。数据是这样的:
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]
})
我想计算每个球队每年的排名,然后跟踪球队每年排名的变化。 我想在 pandas.
中用向上和向下箭头显示排名变化结果一定是这样的:
您可以使用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 → → →