小编zer*_*ark的帖子

如何根据pandas中的另一列数组对一列数组进行排序?

我有这样的数据帧:

df1= pd.DataFrame({
    'col1': [np.asarray([1,4,3,2]), np.asarray([9,10,7,5]), np.asarray([100,120,10,22])],
    'col2': [np.asarray([0,1,4,5]), np.asarray([100,101,102,103]), np.asarray([10,11,12,13])]
})

df1
                 col1                  col2
0        [1, 4, 3, 2]          [0, 1, 4, 5]
1       [9, 10, 7, 5]  [100, 101, 102, 103]
2  [100, 120, 10, 22]      [10, 11, 12, 13]
Run Code Online (Sandbox Code Playgroud)

我想根据第1列中数组的值对第2列中的数组值进行排序.

这是我的解决方案:

sort_idx = df1['col1'].apply(np.argsort).values
for rowidxval, (index, row) in enumerate(df1.iterrows()):
    df1['col1'][index] = df1['col1'][index][sort_idx[rowidxval]]
    df1['col2'][index] = df1['col2'][index][sort_idx[rowidxval]]
Run Code Online (Sandbox Code Playgroud)

有没有一种优雅,pythonic的方式来做它而不是蛮力排序数据帧行?如果我想根据第1列中的值重新排序多个列,该怎么办?

python dataframe pandas

3
推荐指数
1
解决办法
57
查看次数

标签 统计

dataframe ×1

pandas ×1

python ×1