【问题标题】:How to center values in my dictionary by one of keys values from it?如何通过其中一个键值将我的字典中的值居中?
【发布时间】:2021-04-29 18:53:41
【问题描述】:

我有一本字典:

{'A1': array([1.        , 0.8787]),
 'A2': array([ 0.73376, -0.14261]),
 'A3': array([0.9179 , 0.59273]),
 'A4': array([ 0.869011, -0.32241])}

我想将这些值(坐标)居中,以便 A1 具有 array([0 , 0]。我该怎么做?我知道我可以应用 np.linalg.norm 进行输入,但我没有不知道怎么办

【问题讨论】:

    标签: python python-3.x function numpy centering


    【解决方案1】:
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(
    {'A1': np.array([1.        , 0.8787]),
     'A2': np.array([ 0.73376, -0.14261]),
     'A3': np.array([0.9179 , 0.59273]),
     'A4': np.array([ 0.869011, -0.32241])})
    
    df = df.sub(df['A1'], axis=0)
    
    print(df)
    
        A1       A2       A3        A4
    0  0.0 -0.26624 -0.08210 -0.130989
    1  0.0 -1.02131 -0.28597 -1.201110
    

    更新:没有熊猫 -

    import numpy as np
    
    d = {'A1': np.array([1.        , 0.8787]),
     'A2': np.array([ 0.73376, -0.14261]),
     'A3': np.array([0.9179 , 0.59273]),
     'A4': np.array([ 0.869011, -0.32241])}
    
    print({k: v-d['A1'] for k,v in d.items()})
    # {'A1': array([0., 0.]), 'A2': array([-0.26624, -1.02131]), 'A3': array([-0.0821 , -0.28597]), 'A4': array([-0.130989, -1.20111 ])}
    

    【讨论】:

    • 谢谢,但我不需要它是一个数据框,它仍然必须是一个字典
    • 添加了纯字典选项
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2020-09-16
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多