Pandas 处理丢失数据

时间:2023-03-09 04:59:07
Pandas  处理丢失数据

处理丢失数据

import pandas as pd
from pandas import Series, DataFrame
import numpy as np

有两种丢失数据:

  • 1. None

    None是Python自带的,其类型为python object。因此,None不能参与到任何计算中。

  • 2. np.nan(NaN)

    np.nan是浮点类型,能参与到计算中。但计算的结果总是NaN。

3. pandas中的None与NaN

1) pandas中None与np.nan都视作np.nan

  • 创建 DataFarme
#创建DataFrame,给其中某些元素赋值为nan

df = DataFrame(data=np.random.randint(0,100,size=(10,12)))
# df.iloc[横向坐标,纵向坐标] = 值
df.iloc[3,6] = None
df.iloc[5,2] = None
df.iloc[8,8] = None
df.iloc[1,4] = np.nan
df

2) pandas处理空值操作

  • isnull()
  • notnull()
  • dropna(): 过滤丢失数据
  • fillna(): 填充丢失数据
#创建DataFrame,给其中某些元素赋值为nan

df.isnull().any(axis=1)
df.notnull().all(axis=1) df.loc[df.notnull().all(axis=1)]

(1)判断函数

  • isnull()
  • notnull()
df.isnull().any(axis=1)  # 1 横向 默认 0 纵向

df.notnull().all(axis=1) 

# 对空的 删除处理
df.loc[df.notnull().all(axis=1)]
  • df.dropna() 可以选择过滤的是行还是列(默认为行): axis中0表示行,1表示的列
df.dropna(axis=0) # 直接对空值进行删除处理
df.dropna(axis=1)

填充函数 Series/DataFrame

  • fillna() :value和method参数
# 1 横向向后补空 0 向下  可以选择前向填充还是后向填充
df.fillna(method='ffill',axis=0)
df.fillna(method='bfill',axis=1)
# method 控制填充的方式 bfill ffill

pandas 读取: excel

df = pd.read_excel('测试数据.xlsx')
df.head() # 对数据进行筛选
df_ = df[['time',1,2,3,4]]
df_ # 对空值进行 删除 处理
df_.dropna(axis=0) # 对空值进行 补植 处理 向下 补植
df_.fillna(method='ffill',axis=0,inplace=True) # 判断是否还存在空值
df_.isnull().any(axis=0)

pandas读写excel文件

  • 依赖: pip install openpyxl
from pymysql import Connect

# 读取数据库中的文件
conn = Connect(host='127.0.0.1', port=3306, user='root', passwd='', charset='utf8', db='40exercises')
cursor = conn.cursor()
sql = "select * from student"
count = cursor.execute(sql)
res = cursor.fetchall() print(count, res)
print(cursor.description)
data = pd.DataFrame(list(ree), columns=[i[0] for i in cursor.description]) # 使用pandas读取excel文件
xls_file=pd.ExcelFile('./data/workbook.xls')
xls_file.sheet_names#显示出读入excel文件中的表名字
table1=xls_file.parse('first_sheet')
table2=xls_file.parse('second_sheet') xlsx_file=pd.ExcelFile("./demo.xlsx")
x1=xlsx_file.parse(0)
x2=xlsx_file.parse(1) # excel文件的写出
# data.to_excel("abc.xlsx",sheet_name="abc",index=False,header=True)
# 该条语句会运行失败,原因在于写入的对象是np数组而不是DataFrame对象,只有DataFrame对象才能使用to_excel方法。 DataFrame(data).to_excel("abc.xlsx",sheet_name="123",index=False,header=True) #excel文件和pandas的交互读写,主要使用到pandas中的两个函数,一个是pd.ExcelFile函数,一个是to_excel函数