如何计算数据帧中有多少点比其他点“更好”?

2024-06-07 05:38:26 发布

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

我在熊猫中有一个数据帧,看起来像这样:

>>> df[1:3]
     0      1      2     3     4    5     6     7     8
1 -0.59  -99.0  924.0  20.1   5.0  4.0  57.0  19.0   8.0
2 -1.30 -279.0  297.0  16.1  30.0  4.4  63.0  19.0  10.0

数据帧中的点数约为1000。 给定一组列,我想找出每个点比另一个“好”多少次? 给定一组n列,如果一个点在其中至少一列中更好,而在其他列中相等,那么它就比另一个点更好。 在一列中较好而在n-1中较差的点不被认为是较好的,因为它至少比另一列中的点好。你知道吗

Edit1:示例:

>>> df
     0      1      2  
1 -0.59  -99.0   924.0 
2 -1.30  -279.0  297.0 
3  2.00  -100.0  500.0
4  0.0   0.0     0.0 

如果只考虑第0列,则结果为:

1 - 1
2 - 0
3 - 3
4 - 2

因为点1(-0.59)对于列1只比点2好。你知道吗

以列-0和1为例:

1 - 1 (only for point 2 all values i.e. column 0 and column 1 are either smaller than point 1 or lesser)
2 - 0 (since no point is has any lesser than this in any dimension)
3 - 1 (point 2)
4 - 2 (point 1 and 2)

编辑2: 也许,像这样一个函数,当给定一个数据帧、一个点(点的索引)和一组列时,它可以给出每个列子集该点比其他点好多少倍的计数。你知道吗

def f(p, df, c):
    """returns
       A list : L = [(c1,n), (c2,m)..]
       where c1 is a proper subset of c and n is the number of times that this point was better than other points."""

Tags: andof数据示例dfisanycolumn
1条回答
网友
1楼 · 发布于 2024-06-07 05:38:26

对每列分别排序
通过对每列进行排序,我可以确切地看到您所在的特定行在该列中的其他行数大于。你知道吗

d1 = df.rank().sub(1)
d1

enter image description here

要解决您的问题,逻辑上必须是这样一种情况:对于某一行,行元素中的最小秩正好是该行中每个元素都大于的其他行的数目。你知道吗

对于前两列[0, 1],可以通过取d1的最小值来计算

我使用它来比较原始的前两列和列

pd.concat([df.iloc[:, :2], d1.iloc[:, :2]], axis=1, keys=['raw', 'ranked'])

enter image description here

取上述最小值。你知道吗

d1.iloc[:, :2].min(1)

1    1.0
2    0.0
3    1.0
4    2.0
dtype: float64

把结果放在原始数据和等级旁边,这样我们就可以看到它

pd.concat([df.iloc[:, :2], d1.iloc[:, :2], d1.iloc[:, :2].min(1)],
          axis=1, keys=['raw', 'ranked', 'results'])

enter image description here

当然,这与你的预期结果是一致的。你知道吗

相关问题 更多 >