将带有缺失值的 Pandas 数据框转换为 NumPy 数组,保留缺失值作为 np.nan。考虑以下数据帧:
<code class="python">index = [1, 2, 3, 4, 5, 6, 7] a = [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1] b = [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan] c = [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan] df = pd.DataFrame({'A': a, 'B': b, 'C': c}, index=index) df = df.rename_axis('ID') print(df)</code>
输出:
A B C ID 1 NaN 0.2 NaN 2 NaN NaN 0.5 3 NaN 0.2 0.5 4 0.1 0.2 NaN 5 0.1 0.2 0.5 6 0.1 NaN 0.5 7 0.1 NaN NaN
使用 to_numpy() 方法将数据帧转换为缺失值表示为 np.nan 的 NumPy 数组:
<code class="python">import numpy as np import pandas as pd np_array = df.to_numpy() print(np_array)</code>
输出:
[[ nan 0.2 nan] [ nan nan 0.5] [ nan 0.2 0.5] [ 0.1 0.2 nan] [ 0.1 0.2 0.5] [ 0.1 nan 0.5] [ 0.1 nan nan]]
如果需要保留结果数组,使用 DataFrame.to_records() 创建 NumPy 结构化数组:
<code class="python">import numpy as np import pandas as pd structured_array = df.to_records() print(structured_array)</code>
输出:
rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)], dtype=[('ID', 'O'), ('A', '<i8'), ('B', '<i8'), ('B', '<i8')])
以上是如何将带有缺失值的 Pandas DataFrame 转换为保留 NaN 的 NumPy 数组?的详细内容。更多信息请关注PHP中文网其他相关文章!