对连接的熊猫数据框进行排序

Kar*_*kar 2 python sorting concat pandas

我想连接两个熊猫数据框AB然后按两列对它们进行排序,'geohash'然后'timestamp'

A
    geohash  timestamp
0   a2a      15
1   b3a      14

B
    geohash  timestamp
0   a2b      15
1   b3b      14
Run Code Online (Sandbox Code Playgroud)

AB = pd.concat([A,B],ignore_index=True)
AB.sort_values(['geohash','timestamp'])
Run Code Online (Sandbox Code Playgroud)

我预计

AB
    geohash  timestamp
0   a2a      15
1   a2b      15
2   b3a      14
3   b3b      14
Run Code Online (Sandbox Code Playgroud)

但我得到

AB
    geohash  timestamp
0   a2a      15
1   b3a      14
2   a2b      14
3   b3b      15
Run Code Online (Sandbox Code Playgroud)

为什么大熊猫AB不对整个数据框进行排序?

joh*_*ase 5

sort_values不会发生在原地。所以当你运行时:

AB.sort_values(['geohash','timestamp'])
Run Code Online (Sandbox Code Playgroud)

它不是更新AB而是返回副本

AB.sort_values(['geohash','timestamp'], inplace=True)
Run Code Online (Sandbox Code Playgroud)

会更新 AB

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

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

geohash timestamp
0   a2a 15
2   a2b 15
1   b3a 14
3   b3b 15
Run Code Online (Sandbox Code Playgroud)