【Pandas】检查是否有空值、处理空值

1.创建有空值的DataFrame
import numpy as np
import pandas as pd

dates = pd.date_range("20200307", periods=4)
df1 = pd.DataFrame(np.arange(12).reshape(4, 3), index=dates, columns=["A", "B", "C"])
df2 = pd.DataFrame(df1, index=dates, columns=["A", "B", "C", "D"])  # 新增D列,却不赋值,NaN表示空值
print(df2)
# 打印输出:
#             A   B   C   D
# 2020-03-07  0   1   2 NaN
# 2020-03-08  3   4   5 NaN
# 2020-03-09  6   7   8 NaN
# 2020-03-10  9  10  11 NaN

2.检查是否有空值
print(df2.isnull())  # 是空值返回True,否则返回False
print(np.any(df2.isnull()))  # 只要有一个空值便会返回True,否则返回False
print(np.all(df2.isnull()))  # 全部值都是空值便会返回True,否则返回False
# 输出结果:
#                 A      B      C     D
# 2020-03-07  False  False  False  True
# 2020-03-08  False  False  False  True
# 2020-03-09  False  False  False  True
# 2020-03-10  False  False  False  True
# True
# False
3.给NaN赋值

df2.iloc[0, 3] = 10  # 直接给某个位置赋值
print(df2)
# 打印输出:
#            A   B   C     D
# 2020-03-07  0   1   2  10.0
# 2020-03-08  3   4   5   NaN
# 2020-03-09  6   7   8   NaN
# 2020-03-10  9  10  11   NaN

series = pd.Series([11, 12, 13], index=dates[1:4])
df2["D"] = series  # 同时给D列赋多个值
print(df2)
# 打印输出:
#             A   B   C     D
# 2020-03-07  0   1   2   NaN
# 2020-03-08  3   4   5  11.0
# 2020-03-09  6   7   8  12.0
# 2020-03-10  9  10  11  13.0

4.去除有空值的行或列
df2.loc["2020-03-10", ["A", "B", "C"]] = [11, 12, 15]
df2.fillna("null")  # 把空值填充成null

# dropna(axis,how,subset)方法会删除有空值的行或列,
# axis为0是行,axis为1是列,
# how为any时该行或列只要有一个空值就会删除,all是全都是空值才删除
# subset是一个列表,指定某些列
df2.dropna(axis=0, how="any", subset=["A", "D"])
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰冷的希望

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值