zer*_*ark 3 python dataframe 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列中的值重新排序多个列,该怎么办?
绝不推荐使用列中的列表(混合dtypes和可变dtypes会在代码中引入瓶颈和性能降低),但您可以使用列表解析尽可能快地完成此操作:
df['col2'] = [np.array(y)[np.argsort(x)] for x, y in zip(df.col1, df.col2)]
df
col1 col2
0 [1, 4, 3, 2] [0, 5, 4, 1]
1 [9, 10, 7, 5] [103, 102, 100, 101]
2 [100, 120, 10, 22] [12, 13, 10, 11]
Run Code Online (Sandbox Code Playgroud)
如果它们都是数组,则解决方案简化:
df['col2'] = [y[x.argsort()] for x, y in zip(df.col1, df.col2)]
df
col1 col2
0 [1, 4, 3, 2] [0, 5, 4, 1]
1 [9, 10, 7, 5] [103, 102, 100, 101]
2 [100, 120, 10, 22] [12, 13, 10, 11]
Run Code Online (Sandbox Code Playgroud)
有关与性能相关的问题的更多信息,请参阅带有pandas的For循环中的 "混合dtypes"部分- 我应该何时关注?.
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |