alb
alb

Reputation: 215

Fill missing values with mean until getting a certain shape in numpy

How can I convert an array of shape (22,1) into an array of (24,1)? How can I fill those missing values?

i.e My array with shape (22,1).

array([[365.],
       [173.],
       [389.],
       [173.],
       [342.],
       [173.],
       [294.],
       [165.],
       [246.],
       [142.],
       [254.],
       [142.],
       [357.],
       [260.],
       [389.],
       [339.],
       [389.],
       [339.],
       [381.],
       [410.],
       [381.],
       [410.]])

How can I fill the two missing numbers with the average? Furthermore, if I have an array of shape (19,1) would I be able to fill until shape (24,1)?

Upvotes: 1

Views: 294

Answers (2)

Alain T.
Alain T.

Reputation: 42133

You could use the pad() function:

import numpy as np
A = np.array([[365.],
       [173.],
       [389.],
       [173.],
       [342.],
       [173.],
       [294.],
       [165.],
       [246.],
       [142.],
       [254.],
       [142.],
       [357.],
       [260.],
       [389.],
       [339.],
       [389.],
       [339.],
       [381.],
       [410.],
       [381.],
       [410.]])

...

B = np.pad(A,((0,24-A.shape[0]),(0,0)),'mean')
print(B)

[[365.        ]
 [173.        ]
 [389.        ]
 [173.        ]
 [342.        ]
 [173.        ]
 [294.        ]
 [165.        ]
 [246.        ]
 [142.        ]
 [254.        ]
 [142.        ]
 [357.        ]
 [260.        ]
 [389.        ]
 [339.        ]
 [389.        ]
 [339.        ]
 [381.        ]
 [410.        ]
 [381.        ]
 [410.        ]
 [296.04545455]
 [296.04545455]]

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

Use a.mean() for the average, then concatenate:

np.concatenate((a,[[a.mean()]] * (24-len(a))))

Upvotes: 1

Related Questions