pandas 用numpy矢量化算法

avkwfej4  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(74)

我有两个1和0的数组:

a = [1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]
b = [0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1]

字符串
我想确保“1”总是“跳跃”数组,因为我从左到右,从来没有出现在同一个数组中两次,然后才出现在另一个数组。

a = [1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]
b = [0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]


我可以使用pandas和迭代来实现:

df = pd.DataFrame({"A": a, "B": b, })
df2 = df[(df.A > 0) | (df.B > 0)]
i = 0
for idx in df2.index:
    try:       
        if df2.at[idx, 'A'] == df2.at[df2.index[i + 1], 'A']:
            df.at[idx, 'A'] = 0
        if df2.at[idx, 'B'] == df2.at[df2.index[i + 1], 'B']:
            df.at[idx, 'B'] = 0
        i += 1
    except IndexError:
        pass


但是效率不高。我如何将其矢量化以使其更快?

w80xi6nr

w80xi6nr1#

IIUC,尝试:

df2 = df[(df.A > 0) | (df.B > 0)]
df2 = df2[df2.B != df2.B.shift(-1)]

df.loc[~df.index.isin(df2.index)] = 0
print(df)

字符串
印刷品:

A  B
0   1  0
1   0  1
2   0  0
3   1  0
4   0  1
5   0  0
6   0  0
7   0  0
8   0  0
9   0  0
10  0  0
11  0  0
12  1  0
13  0  0
14  0  0
15  0  0
16  0  0
17  0  0
18  0  0
19  0  1


编辑:逐步解释:
只保留行中任何地方有1值的索引:

df2 = df[(df.A > 0) | (df.B > 0)]
print(df2)


印刷品:

A  B
0   1  0
1   0  1
3   1  0
4   0  1
9   1  0
16  0  1
19  0  1


我们看到我们只需要A和B之间交替变化的索引(所以我们需要在这里去掉索引16)。
我们知道B必须交替,所以我们移动B列并进行比较:

df2["tmp"] = df2.B != df2.B.shift(-1)

    A  B    tmp
0   1  0   True
1   0  1   True
3   1  0   True
4   0  1   True
9   1  0   True
16  0  1  False
19  0  1   True


索引16的值为False,所以我们只保留其他索引:

df2 = df2[df2.B != df2.B.shift(-1)]
df.loc[~df.index.isin(df2.index)] = 0
print(df)


打印最终的df。

相关问题