对串联的 pandas 数据帧进行排序

Sorting a concatenated pandas dataframe

我想连接两个 pandas 数据帧 AB,然后按两列 'geohash''timestamp'

对它们进行排序
A
    geohash  timestamp
0   a2a      15
1   b3a      14

B
    geohash  timestamp
0   a2b      15
1   b3b      14

之后
AB = pd.concat([A,B],ignore_index=True)
AB.sort_values(['geohash','timestamp'])

我希望

AB
    geohash  timestamp
0   a2a      15
1   a2b      15
2   b3a      14
3   b3b      14

但我明白了

AB
    geohash  timestamp
0   a2a      15
1   b3a      14
2   a2b      14
3   b3b      15

为什么 pandas 不对整个数据帧进行排序 AB

sort_values没有发生到位。所以当你 运行:

AB.sort_values(['geohash','timestamp'])

它没有更新 AB 而是返回一个副本

AB.sort_values(['geohash','timestamp'], inplace=True)

会更新AB

或者,您可以将排序后的数据框分配给新变量

AB_sorted = AB.sort_values(['geohash','timestamp'])
AB_sorted 

geohash timestamp
0   a2a 15
2   a2b 15
1   b3a 14
3   b3b 15