基于列值重新排列数据帧行

2024-10-01 15:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个pandas数据帧:

        artist               track   class1  class2     class3
0   Portishead               Roads   0.00    1.00          0.0
1  Yo La Tengo     Our Way to Fall   0.14    0.86          0.0
2    Radiohead  Fake Plastic Trees   0.03    0.97          0.0

这两个用户输入变量:

^{pr2}$

从这些变量中我想在数据帧上迭代, 在所选的class2中找到最接近input_value的值,然后对数据帧行重新排序,如下所示:

        artist               track   class1  class2     class3
1  Yo La Tengo     Our Way to Fall   0.14    0.86          0.0
2    Radiohead  Fake Plastic Trees   0.03    0.97          0.0
0   Portishead               Roads   0.00    1.00          0.0

其中,类2值的接近程度决定了行的顺序。在

0.86最接近0.800.97次之,依此类推)

到目前为止,我只找到了最接近的值,代码如下:

for col in df.ix[:,'class1':'class3']:
    if col == input_class:
        print min(df[col] - input_value)

但我离我的目标还有点远。谁能给我指出正确的方向吗?在


Tags: 数据inputartistourcoltracklaway
1条回答
网友
1楼 · 发布于 2024-10-01 15:35:42

尝试argsort在差异上加iloc

df = df.iloc[(df[input_class] - input_value).argsort()]

df
        artist               track  class1  class2  class3
1  Yo La Tengo     Our Way to Fall    0.14    0.86     0.0
2    Radiohead  Fake Plastic Trees    0.03    0.97     0.0
0   Portishead               Roads    0.00    1.00     0.0

或者,您可以使用np.argsort达到相同的效果。在

^{pr2}$

使用reset_index重新排序索引。在

df.result.reset_index(drop=1)     
        artist               track  class1  class2  class3
0  Yo La Tengo     Our Way to Fall    0.14    0.86     0.0
1    Radiohead  Fake Plastic Trees    0.03    0.97     0.0
2   Portishead               Roads    0.00    1.00     0.0

相关问题 更多 >

    热门问题