【问题标题】:How to Compare Elements in itertools.combinations?如何比较 itertools.combinations 中的元素?
【发布时间】:2019-07-09 07:24:07
【问题描述】:

我想比较两个series中的元素。

0    1
1    3
2    4
3    2
4    4
Name: s1, dtype: int32
0    3
1    3
2    0
3    5
4    1
Name: s2, dtype: int64 

为了方便比较series,我使用了itertools.combinations

x = combinations(s1, 2)
y = combinations(s2, 2)

结果x

(1, 3)
(1, 4)
(1, 2)
(1, 4)
(3, 4)
(3, 2)
(3, 4)
(4, 2)
(4, 4)
(2, 4)

(3, 3)
(3, 0)
(3, 5)
(3, 1)
(3, 0)
(3, 5)
(3, 1)
(0, 5)
(0, 1)
(5, 1)

比较的方法部分类似于 Kendall 的 tau 距离。 x (x1, x2) 中的对,以及 y (y1, y2) 中的对。如果x1 > x2y1 > y2,或者x1 < x2y1 < y2,那么score = score+1;否则,score = score。但到目前为止,我仍然无法比较对中的元素。


我收到m1m2m1|m2

m1 :

0    False
1    False
2    False
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

平方米:

0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

m1|m2:

0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

我得到了和你一样的结果。我不知道为什么它加起来这么多时间。


m1 和 m2 都包含默认的所有错误值。确实如此,而且目前的结果在理想情况下是正确的。但我希望score 每次(m1 | m2) == true 加 1。

score
0
0
1
0
0
0
0
0
0
0

上述分数的理想结果。

【问题讨论】:

    标签: python python-3.x pandas jupyter-notebook


    【解决方案1】:

    您可以从输出中创建DataFrame,然后按条件修改数据:

    #changed data for better sample
    s1 = pd.Series([1,3,4,2,4])
    s2 = pd.Series([3,4,0,5,8])
    
    x = combinations(s1, 2)
    y = combinations(s2, 2)
    
    dfx = pd.DataFrame(list(x)).rename(columns=lambda x: x+1).add_prefix('x')
    dfy = pd.DataFrame(list(y)).rename(columns=lambda x: x+1).add_prefix('y')
    df = pd.concat([dfx, dfy], axis=1)
    
    m1 = (df.x1 > df.x2) & (df.y1 > df.y2)
    m2 = (df.x1 < df.x2) & (df.y1 < df.y2)
    m = m1 | m2
    
    print (m)
    0     True
    1    False
    2     True
    3     True
    4    False
    5    False
    6     True
    7    False
    8    False
    9     True
    dtype: bool
    

    df['score'] = np.where(m, m.cumsum(), 0)
    print (df)
       x1  x2  y1  y2  score
    0   1   3   3   4      1
    1   1   4   3   0      0
    2   1   2   3   5      2
    3   1   4   3   8      3
    4   3   4   4   0      0
    5   3   2   4   5      0
    6   3   4   4   8      4
    7   4   2   0   5      0
    8   4   4   0   8      0
    9   2   4   5   8      5
    

    【讨论】:

    • 结果有问题。对于row[1]1 4 3 0,1 &lt; 4, 3 &gt; 0,不应该加分,其他行也有同样的问题。
    • @JerryChen - 所以你问题中的条件是错误的? If x1 &gt; x2 and y1 &gt; y2, or x1 &lt; x2 and y1 &lt; y2, then score = score+1; otherwise, score = score. ?
    • @JerryChen - 按需更改 &lt;&gt;
    • 已在上面编辑。除了score,输出都是正确的。顺便说一句,谢谢你的耐心,你真的帮了我很多。
    • 没错!从你那里学到了很多东西,你真的拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多