• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

  • 共95篇

    python3.X - 数据分析 - Pandas

关闭

返回栏目

关闭

返回python3.X - 数据分析 - Pandas栏目

54 - 内容 - df.where() - NaN转换为None

作者:

贺及楼

成为作者

更新日期:2024-08-14 12:55:45

df.where()NaN转换为None

NaN转None

  1. import numpy as np
  2. import pandas as pd
  3. df = pd.DataFrame(data=[{"A":"one", "B":"a", "C":11}, {"A":"two", "B":np.NaN, "C":22}, {"A":"one", "B":1, "C":12}])
A B C
0 one a 11
1 two NaN 22
2 one 1 12
  1. ## 将非空数据保留,空数据用None替换
  2. df = df.where(df.notnull(), None)
  3. print(df)
A B C
0 one a 11
1 two None 22
2 one 1 12
  1. ## 将非空数据保留,空数据用0替换
  2. df = df.where(df.notnull(), 0)
  3. print(df)
A B C
0 one a 11
1 two 0 22
2 one 1 12

NaT转0days

  1. import numpy as np
  2. import pandas as pd
  3. df = pd.DataFrame(data=[
  4. {"A":"one", "B":pd.Timedelta(0,unit="s"), "C":11},
  5. {"A":"two", "B":pd.NaT, "C":22},
  6. {"A":"one", "B":pd.Timedelta(0,unit="s"), "C":12}])
A B C
0 one 0 days 11
1 two NaT 22
2 one 0 days 12
  1. # 将非空数据保留,空数据用0替换
  2. df = df.where(df.notnull(), pd.Timedelta(0,unit="s"))
  3. df["B"] = df["B"].where(df["B"].notnull(), pd.Timedelta(0,unit="s"))
  4. print(df)
A B C
0 one 0 days 11
1 two 0 days 22
2 one 0 days 12