为什么在对数据帧进行排序后 loc 和 iloc 之间有所不同?



我有一个带有日期列的数据框。按日期排序后,我希望按排序顺序从数据帧中读取数据。但是,使用 iloc 仅提供排序后的数据,但使用 loc 似乎保留排序前的序列。有没有办法规避这个问题。我想使用"loc",但从数据帧中获取排序数据。

import pandas as pd
client_dictionary = {'name': ['Michael', 'Ana', 'Sean'],
'country': ['UK', 'UK', 'USA'],
'age': [10, 51, 13],
'latest date active': ['07-05-2019', '23-12-2019', '03-04-2016']}
df = pd.DataFrame(client_dictionary)
df.head()
df['latest date active'] = df['latest date active'].astype('datetime64[ns]')
df.sort_values(by='latest date active', inplace=True)
df.reset_index()
for i in range(0, len(df)):
print("With loc: " + str(df.loc[i, 'latest date active']) + ", with iloc: " + str(df.iloc[i, 3]))

当上面的代码运行时,我得到以下输出:

With loc: 2019-07-05 00:00:00, with iloc: 2016-03-04 00:00:00
With loc: 2019-12-23 00:00:00, with iloc: 2019-07-05 00:00:00
With loc: 2016-03-04 00:00:00, with iloc: 2019-12-23 00:00:00

重置索引时,必须重新分配数据帧或传递inplace参数:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html

df.sort_values(by='latest date active', inplace=True)
df.reset_index(inplace=True)

现在它们应该是等效的。

最新更新