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

Time:10-18

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)?

CodePudding user response:

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

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

CodePudding user response:

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]]
  • Related