Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Any solution for merging 2D array into a list?

I’m working on a linear regression with python for my school project. And I want to merge my 7*12 2D-array into 1D list.
Here’s my original array.

y = df["fatalProb"].values.reshape(7,12)
print(y)
[[0.3725 0.4336 0.537  0.392  0.233  0.2892 0.2721 0.2392 0.2281 0.2689
  0.2898 0.2825]
 [0.3112 0.3936 0.3874 0.2793 0.2416 0.275  0.2802 0.2587 0.2583 0.258
  0.2906 0.2927]
 [0.3486 0.3278 0.3836 0.3041 0.2477 0.2734 0.276  0.2903 0.2531 0.2659
  0.2928 0.2896]
 [0.3044 0.4032 0.3665 0.3275 0.2939 0.2882 0.3089 0.2949 0.2547 0.2699
  0.2973 0.2869]
 [0.3488 0.3651 0.4307 0.3361 0.2833 0.3035 0.3051 0.2898 0.2695 0.271
  0.2787 0.3034]
 [0.3559 0.3357 0.4075 0.3428 0.2834 0.3156 0.2952 0.2992 0.2795 0.2806
  0.2905 0.267 ]
 [0.3965 0.3814 0.4735 0.3813 0.3089 0.3105 0.3282 0.3047 0.2834 0.2974
  0.2737 0.2986]]

I wanted my y to be 12-length list.
It’s a list with all the values added that has a same index in each lists. (sorry for the bad English)

e.g.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[a,b,c],[d,e,f],[g,h,i]] to [a+d+g,b+e+h,c+f+i]

I thought about using list comprehension. But I was not so happy to use

y = [y[0][j]+y[1][j]+y[2][j]+y[3][j]+y[4][j]+y[5][j]+y[6][j] for j in range(len(y[0]))]

>Solution :

you can use :

l=[]
k=[]
for j in range(len(y[0])):
    for i in range(0,7):
        l.append(y[i][j])
    k.append(sum(l))
y=k

out :

print(y)
    [2.4379,
     5.0783000000000005,
     8.0645,
     10.4276,
     12.319400000000002,
     14.3748,
     16.4405,
     18.417299999999997,
     20.243899999999996,
     22.155599999999993,
     24.168999999999997,
     26.189699999999995]

check len y :

len(y)
12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading