侃侃无极
“对象” dtype 也给我带来了问题。但你astype(np.float64)确实为我工作。谢谢!print("Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:")A = np.array([1., 2., 3., np.nan]); print('A:', A, A.dtype)B = pd.DataFrame([[1., 2., 3., np.nan,], [1, 2, 3, '4']] ).to_numpy(); print('B:', B, B.dtype, '\n')print('Converting vanilla A is fine:\n', np.nan_to_num(A, nan=-99), '\n')print('But not B:\n', np.nan_to_num(B, nan=-99), '\n')print('Not even this slice of B, \nB[0, :] : ', B[0, :])print(np.nan_to_num(B[0, :], nan=-99), '\n')print('The astype(np.float64) does the trick here:\n', np.nan_to_num(B[0, :].astype(np.float64), nan=-99), '\n\n')输出:Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:A: [ 1. 2. 3. nan] float64B: [[1.0 2.0 3.0 nan] [1.0 2.0 3.0 '4']] object Converting vanilla A is fine: [ 1. 2. 3. -99.] But not B: [[1.0 2.0 3.0 nan] [1.0 2.0 3.0 '4']] Not even this slice of B, B[0, :] : [1.0 2.0 3.0 nan][1.0 2.0 3.0 nan] The astype(np.float64) does the trick here: [ 1. 2. 3. -99.]