Python的pandas库的用法(五)处理丢失数据

本文介绍使用Python的Pandas库进行数据处理的方法,包括创建DataFrame,处理缺失数据,如删除含有NaN的行或列,以及如何用特定值填充缺失项。通过实际代码演示了数据清洗的常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd
import numpy as np

dates = pd.date_range('20190101',periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)),index=dates,columns=['A','B','C','D'])
df.iloc[0,1] = np.nan
df.iloc[1,2] = np.nan

print(df)

选择丢掉数据缺失的某行或某列

# axis = 0 按行来dorp
print(df.dropna(axis=0,how ='any')) # 有任何nan就丢掉

# axis = 1 按列来drop
print(df.dropna(axis=1,how='any')) # how={‘any’,‘all’} 默认how='any'

print(df.dropna(axis=0,how='all')) 

填充缺失数据

print(df)
print(df.fillna(value=0))

检查是否缺失数据

print(df.isnull()) # 缺值的返回True,否则返回False

如果DataFrame里数据很多怎么判断是否缺值?

print(np.any(df.isnull())==True)

# 至少包含一个缺失值时返回Ture

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值