首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中有效地只计算此操作的上三角形?

如何在Python中有效地只计算此操作的上三角形?
EN

Stack Overflow用户
提问于 2018-07-04 03:31:44
回答 1查看 74关注 0票数 2

我正在做一个计算,用来测量pd.Series中的值之间的差异。虽然这是一个向量运算,而且是一次性完成的,但我觉得它的效率很低,因为它还计算下三角形和上三角形的值(本质上是值* -1)。我只想要上三角形。

我怎么才能只计算上面三角形的值(而不是临时索引它们)?

我可以将pandas转换为numpy,如果它将显着提高操作速度。

代码语言:javascript
复制
profile = np.log(pd.Series({'Attr000001': 17511, 'Attr000002': 4, 'Attr000003': 8078, 'Attr000004': 1, 'Attr000005': 1716}))
idx_attrs = profile.index

d_ratio = dict()
for j,id_attr in enumerate(idx_attrs):
    d_ratio[id_attr] = (profile[id_attr] - profile).to_dict()
df_ratio = pd.DataFrame(d_ratio).T
# print(df_ratio)
#             Attr000001  Attr000002  Attr000003  Attr000004  Attr000005
# Attr000001    0.000000    8.384290    0.773685    9.770585    2.322833
# Attr000002   -8.384290    0.000000   -7.610605    1.386294   -6.061457
# Attr000003   -0.773685    7.610605    0.000000    8.996900    1.549148
# Attr000004   -9.770585   -1.386294   -8.996900    0.000000   -7.447751
# Attr000005   -2.322833    6.061457   -1.549148    7.447751    0.000000
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-04 03:48:13

避免使用Python for循环。在numpy中,这只是:

代码语言:javascript
复制
>>> profile[:, None] - profile[None, :]
array([[ 0.        ,  8.38429017,  0.77368494,  9.77058453,  2.32283325],
       [-8.38429017,  0.        , -7.61060524,  1.38629436, -6.06145692],
       [-0.77368494,  7.61060524,  0.        ,  8.9968996 ,  1.54914832],
       [-9.77058453, -1.38629436, -8.9968996 ,  0.        , -7.44775128],
       [-2.32283325,  6.06145692, -1.54914832,  7.44775128,  0.        ]])
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51161735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档