將帶有缺失值的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中文網其他相關文章!