简体   繁体   English

Python Sorting Pandas数据框产生随机结果

[英]Python Sorting Pandas dataframe results in random results

I am observing some random sort results for a dataframe that I intend to sort by dates in ascending order. 我正在观察某个数据框的一些随机排序结果,这些结果打算按日期按升序排序。 For multiple runs, most of the runs returns the correct results but for a small number of runs, it returns an incorrect results. 对于多次运行,大多数运行返回正确的结果,但对于少数运行,则返回错误的结果。

            records_df = records_df.groupby(['YEAR','QUARTER','SUPPLIER_ID']).TRANSACTION_DATES.agg({'TRANSACTION_DATES' : lambda x: list(x.unique())}).reset_index()
            # This now sorts in date order
            records_df.sort_values(by=['TRANSACTION_DATES'])

For most runs: TRANSACTION_DATES: [05-Sep-17, 06-Sep-17, 07-Sep-17] 对于大多数跑步:TRANSACTION_DATES:[17年9月5日,17年9月6日,17年9月7日]

For some runs: Incorrect results is seen: 对于某些运行:看到错误的结果:
TRANSACTION_DATES: [06-Sep-17, 07-Sep-17, 05-Sep-17] TRANSACTION_DATES:[17年9月6日,17年9月7日,17年9月5日]

Why is that so since I am already enforcing a sort using sort_values? 为什么会这样,因为我已经在使用sort_values强制执行排序了?

I think your problem is that you are using sort_values without assigning or using the inplace argument. 我认为您的问题是您在使用sort_values而不分配或使用inplace参数。 This means that your sorted dataframe is just disappearing and is not stored anywhere. 这意味着排序后的数据框将消失,并且不会存储在任何地方。

So try: 因此,请尝试:

records_df = records_df.sort_values(by=['TRANSACTION_DATES'])

or 要么

records_df.sort_values(by=['TRANSACTION_DATES'], inplace=True)

For reference, the sort_values docs: 作为参考,sort_values文档:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM