Pandas NaN to None

October 22, 2019

上次處理資料找了一次答案,今天處理資料又用到,記錄一下。

Python Pandas 讀取 csv 檔把 NaN 轉成 None

import pandas as pd
import numpy as np

df = pd.read_csv("xxx.csv", encoding='utf8', header=None, low_memory=False)
df = df.replace({pd.np.nan: None})

2021/05/25 update

今天在用的時候得到一段訊息:

FutureWarning: The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead

為了因應未來新版本變更改寫成下面寫法即可

df = df.replace({np.nan: None})

Profile picture

Written by dsewnr who lives and works in Taiwan has a great enthusiasm for software engineering. Please feel free to contact me by email or Mastodon.