Code Sample, a copy-pastable example if possible
# Your code here
df = pandas.DataFrame({'a': [1, 10, 8, 11, -1],
'b': [1.0, 2.0, 3.0, 3.0, 4.0]})
df.nlargest(3, 'b')
Result:
a b
4 -1 4.0
2 8 3.0
3 11 3.0
2 8 3.0
3 11 3.0
Problem description
[this should explain why the current behaviour is a problem and why the expected output is a better solution.]
Duplicate values in column 'b' is not being handled correctly. The result is different than what "df.sort_values('b', ascending=False).head(3)" produces.
Note: We receive a lot of issues on our GitHub tracker, so it is very possible that your issue has been posted before. Please check first before submitting so that we do not have to handle and close duplicates!
Note: Many problems can be resolved by simply upgrading pandas
to the latest version. Before submitting, please check if that solution works for you. If possible, you may want to check if master
addresses this issue, but that is not necessary.
For documentation-related issues, you can check the latest versions of the docs on master
here:
https://pandas-docs.github.io/pandas-docs-travis/
If the issue has not been resolved there, go ahead and file it in the issue tracker.
Expected Output
a b
4 -1 4.0 2 8 3.0 3 11 3.0
Output of pd.show_versions()
INSTALLED VERSIONS
commit: None python: 2.7.12.final.0 python-bits: 64 OS: Linux OS-release: 4.3.5-smp-808.15.0.0 machine: x86_64 processor: byteorder: little LC_ALL: en_US.UTF-8 LANG: None LOCALE: None.None
pandas: 0.19.2 nose: None pip: None setuptools: None Cython: None numpy: 1.11.1 scipy: 0.15.1 statsmodels: 0.6.1 xarray: None IPython: 2.0.0 sphinx: None patsy: 0.4.1 dateutil: 2.6.0 pytz: 2017.2 blosc: None bottleneck: None tables: 3.1.1 numexpr: 2.5 matplotlib: 1.5.2 openpyxl: None xlrd: 0.9.3 xlwt: None xlsxwriter: None lxml: None bs4: None html5lib: 1.0b8 httplib2: 0.9.2 apiclient: 1.5.5 sqlalchemy: None pymysql: None psycopg2: None jinja2: 2.8 boto: None pandas_datareader: None
[paste the output of pd.show_versions()
here below this line]
Comment From: jreback
IIRC this is fixed in 0.20.3, but this is from 0.21.0
In [2]: df = pd.DataFrame({'a': [1, 10, 8, 11, -1],
...: 'b': [1.0, 2.0, 3.0, 3.0, 4.0]})
...: df.nlargest(3, 'b')
...:
Out[2]:
a b
4 -1 4.0
2 8 3.0
3 11 3.0