I have a dataframe like this:
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]
I want to sort the values of the arrays in column 2 based on the values of the arrays in column 1.
Here's my solution:
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]]
Is there an elegant, pythonic way of doing it instead of brute force sort the dataframe row-wise? What if I want to re-sort more than one column based on the values in column 1?