Updated version takes NaN values into account
Updated version takes NaN values into account