Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

python - How to center values in my dictionary by one of keys values from it?

I have a dictionary:

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

I want to center those values (which are coordinates) so that A1 has array([0 , 0]. How could I do it? I know that I can apply np.linalg.norm to make a entering but I don't know how

question from:https://stackoverflow.com/questions/65893728/how-to-center-values-in-my-dictionary-by-one-of-keys-values-from-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

Update: and without pandas -

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 ])}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...