gpt4 book ai didi

python - 来自 Pandas 数据框的成对矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:37 24 4
gpt4 key购买 nike

我有一个看起来像这样的 pandas 数据框:

             Al01   BBR60   CA07    NL219AAEAMEVAT    MP      NaN     MP      MP AAFEDLRLL    NaN     NaN     NaN     NaNAAGAAVKGV    NP      NaN     NP      NP ADRGLLRDI    NaN     NP      NaN     NaN AEIMKICST    PB1     NaN     NaN     PB1 AFDERRAGK    NaN     NaN     NP      NP AFDERRAGK    NP      NaN     NaN     NaN

有大约一千行和六列。大多数单元格为空 (NaN)。假设不同的列中有文本,我想知道每列中文本的概率是多少。例如,这里的小片段会产生如下内容:

            Al01    BBR60   CA07    NL219Al01        4       0       2       3BBR60       0       1       0       0CA07        2       0       3       3NL219       3       0       3       4

这表示在 Al01 列中有 4 个命中;在这 4 个命中中,没有一个是 BBR60 列中的命中,2 个也是 CA07 列中的命中,3 个是 NL219 列中的命中。等等。

我可以遍历每一列并用值构建一个字典,但这看起来很笨拙。有没有更简单的方法?

最佳答案

您正在执行的操作可以表示为 np.einsum 的应用程序-- 它是每对列之间的内积:

import numpy as np
import pandas as pd

df = pd.read_table('data', sep='\s+')
print(df)
# Al01 BBR60 CA07 NL219
# 0 MP NaN MP MP
# 1 NaN NaN NaN NaN
# 2 NP NaN NP NP
# 3 NaN NP NaN NaN
# 4 PB1 NaN NaN PB1
# 5 NaN NaN NP NP
# 6 NP NaN NaN NaN

arr = (~df.isnull()).values.astype('int')
print(arr)
# [[1 0 1 1]
# [0 0 0 0]
# [1 0 1 1]
# [0 1 0 0]
# [1 0 0 1]
# [0 0 1 1]
# [1 0 0 0]]

result = pd.DataFrame(np.einsum('ij,ik', arr, arr),
columns=df.columns, index=df.columns)
print(result)

产量

       Al01  BBR60  CA07  NL219
Al01 4 0 2 3
BBR60 0 1 0 0
CA07 2 0 3 3
NL219 3 0 3 4

通常当计算归结为数值运算独立于索引时,使用 NumPy 比使用 Pandas 更快。这似乎是这里的情况:

In [130]: %timeit df2 = df.applymap(lambda x: int(not pd.isnull(x)));  df2.T.dot(df2)
1000 loops, best of 3: 1.12 ms per loop

In [132]: %timeit arr = (~df.isnull()).values.astype('int'); pd.DataFrame(np.einsum('ij,ik', arr, arr), columns=df.columns, index=df.columns)
10000 loops, best of 3: 132 µs per loop

关于python - 来自 Pandas 数据框的成对矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com