Pandas 替换 NaN 值

替换Pandas DataFram中的 NaN 值

问题

NaN 代表 Not A Number,是表示数据中缺失值的常用方法之一。它是一个特殊的浮点值,不能转换为 float 以外的任何其他类型。NaN 值是数据分析中的主要问题之一。为了得到理想的结果,对 NaN 进行处理是非常必要的。

方法

用零替换Pandas DataFram中的 NaN 值的方法:

下面以替换为0举例, 可以替换为任意值,依照个人情况考虑。关于上述两个函数的用法,可以参考官方链接,功能很强大。

替换 NaN 值的步骤

df['DataFrame Column'] = df['DataFrame Column'].fillna(0)
df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0)
df.fillna(0)
df.replace(np.nan, 0)

示例

# importing libraries
import pandas as pd
import numpy as np
  
nums = {'Set_of_Numbers': [2, 3, 5, 7, 11, 13, np.nan, 19, 23, np.nan]}
  
# Create the dataframe
df = pd.DataFrame(nums, columns =['Set_of_Numbers'])
  
# Apply the function
df['Set_of_Numbers'] = df['Set_of_Numbers'].fillna(0)
  
# print the DataFrame
df

pandas-replace-nan-1

# importing libraries
import pandas as pd
import numpy as np
  
nums = {'Car Model Number': [223, np.nan, 237, 195, np.nan,
                             575, 110, 313, np.nan, 190, 143, 
                             np.nan],
       'Engine Number': [4511, np.nan, 7570, 1565, 1450, 3786, 
                         2995, 5345, 7777, 2323, 2785, 1120]}
  
# Create the dataframe
df = pd.DataFrame(nums, columns=['Car Model Number'])
  
# Apply the function
df['Car Model Number'] = df['Car Model Number'].replace(np.nan, 0)
  
# print the DataFrame
df

pandas-replace-nan-2

# importing libraries
import pandas as pd
import numpy as np
  
nums = {'Number_set_1': [0, 1, 1, 2, 3, 5, np.nan, 13, 21, np.nan],
       'Number_set_2': [3, 7, np.nan, 23, 31, 41, np.nan, 59, 67, np.nan],
       'Number_set_3': [2, 3, 5, np.nan, 11, 13, 17, 19, 23, np.nan]}
  
# Create the dataframe
df = pd.DataFrame(nums)
  
# Apply the function
df = df.fillna(0)
  
# print the DataFrame
df

pandas-replace-nan-3

# importing libraries
import pandas as pd
import numpy as np
  
nums = {
         'Student Name': [ 'Shrek', 'Shivansh', 'Ishdeep', 'Siddharth', 'Nakul', 'Prakhar', 'Yash', 'Srikar', 'Kaustubh', 'Aditya',  'Manav', 'Dubey'],
        'Roll No.': [ 18229, 18232, np.nan, 18247, 18136, np.nan, 18283, 18310, 18102, 18012, 18121, 18168],
        'Subject ID': [204, np.nan, 201, 105, np.nan, 204, 101, 101, np.nan, 165, 715, np.nan],
       'Grade Point': [9, np.nan, 7, np.nan, 8, 7, 9, 10, np.nan, 9, 6, 8]}

# Create the dataframe
df = pd.DataFrame(nums)
  
# Apply the function
df = df.replace(np.nan, 0)
  
# print the DataFrame
df

pandas-replace-nan-5

参考

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年3月30日 上午9:27
下一篇 2023年3月30日 上午9:30

相关推荐