【问题标题】:sorting pandas dataframe with inf and NaN使用 inf 和 NaN 对 pandas 数据帧进行排序
【发布时间】:2017-08-21 22:55:39
【问题描述】:
我有一个 pandas 数据框,我想按列的降序排序。
Name count
AAAA -1.1
BBBB 0
CCCC -10
DDDD inf
EEEE 3
FFFF NaN
GGGG 30
我希望按降序排序计数并将 inf 和 NaN 行移到末尾。
df.sort('count',ascending = False,na_position="last") 将 NaN 推到最后。如何处理inf?
【问题讨论】:
标签:
sorting
pandas
dataframe
【解决方案1】:
您可以将 inf 值视为 null:
with pd.option_context('mode.use_inf_as_null', True):
df = df.sort_values('count', ascending=False, na_position='last')
df
Out:
Name count
6 GGGG 30.000000
4 EEEE 3.000000
1 BBBB 0.000000
0 AAAA -1.100000
2 CCCC -10.000000
3 DDDD inf
5 FFFF NaN
【解决方案2】:
一种可能的解决方案:
In [33]: df.assign(x=df['count'].replace(np.inf, np.nan)) \
.sort_values('x', ascending=False) \
.drop('x', 1)
Out[33]:
Name count
6 GGGG 30.000000
4 EEEE 3.000000
1 BBBB 0.000000
0 AAAA -1.100000
2 CCCC -10.000000
3 DDDD inf
5 FFFF NaN