首页 > 解决方案 > 如何根据其他列中的值对 Pandas 中的值进行排序?

问题描述

我有这样的数据框:

int_time ID
3 4123 1
5 243 2
7 1232 3
8 3883 4
.. ... ..

我想根据值 id 对 int_time 和 leng 中的值进行排序。所以输出将如下所示:

int_time ID
0 0 1
0 0 2
3 4123 3
4 0 4
5 243 5
6 0 6
7 1232 7
8 3883 8
.. ... ..

换句话说,我想根据 id 中的值更改 int_time 和 leng 的行索引。有人可以帮我吗?

标签: pythonpandasdataframe

解决方案


你可以使用合并 -

n = df['int_time'].max()
new_df = pd.DataFrame({'id': range(1, int(n) + 1)})
new_df = new_df.merge(df, left_on='id', right_on='int_time', how= 'left').fillna(0).drop('id_y', axis=1).rename(columns={'id_x': 'Id'})
print(new_df)

输出-

ID int_time
1 0.0 0.0
2 0.0 0.0
3 3.0 4123.0
4 0.0 0.0
5 5.0 243.0
6 0.0 0.0
7 7.0 1232.0
8 8.0 3883.0

推荐阅读