I have a NumPy matrix like this one (it could have several columns, this is just an example:
JavaScript
x
7
1
array([[nan, nan],
2
[nan, nan],
3
['value 1', nan],
4
[nan, nan],
5
[nan, nan],
6
[nan, 'value 2']], dtype=object)
7
I need to merge all columns in this matrix, replacing nan values with the corresponding non-nan value (if exists). Example output:
JavaScript
1
7
1
array([[nan],
2
[nan],
3
['value 1'],
4
[nan],
5
[nan],
6
['value 2']], dtype=object)
7
Is there a way to achieve this with some built-in function in NumPy?
EDIT: if there is more than one non-nan in single row, I will take the first non-nan value.
Values could be string, float or int
Advertisement
Answer
Find the rows where the first column is nan
. This works because nan!=nan
:
JavaScript
1
2
1
rows = arr[:,0] != arr[:,0]
2
Update the first element of each chosen row with the second element:
JavaScript
1
2
1
arr[rows,0] = arr[rows,1]
2
Select the first column:
JavaScript
1
2
1
arr[:,[0]]
2