数据开发_Python数据预处理_Pandas案例(二)

说明

1.数据预处理
   数据预处理中清洗数据,是重塑数据的步骤之一,将一些不符合程序输入的数据整理成符合相应模式的数据
   数据重塑能力
 2.一些符号说明
    import pandas as pd
    df 是一个数据框  eg:
     df = pd.DataFrame({
     'col_1_nm':['11','22'],
     'col_2_nm':['da','dd']
     })
  列表表达式 有 if 和 else   [num ** 3 if num % 2 == 0 else 0 for num in range(12)]  
            只有 if 时      [num ** 3  for num in range(12) if num % 2 == 0]   过滤功能

数据类型转换

数据类型
   Pandas类型 object    int64   float64  datetime64  
   Python类型 str    int  float datetime
函数
    Numpy和Pandas的查看方式略有不同,一个是 dtype,一个是dtypes
   pandas方法   df.dtype  df.info  size  values index
   Python中函数 type()
-- 读取数据指定类型
df.astype() 强制转换
pd.to_numeric()
pd.to_datetime()

缺失值

  1.缺失值来源: 来源于数据源
              来源于数据操作 merge() 等操作
	 来源于数据操作的情况
	  01. mid_data = pd.merge(exm_input, sap_input, left_on='field_code', right_on='field_code', how='left')
	  02.两个数据框
	     df.append(df2)
	     pd.concat(, axis=1)  pd.concat(, axis=0)
  2.缺失值处理
   数值型和字符串型转换经常遇到空值 / NaN值处理
    1. 删除缺失值:dropna函数    df.dropna(how='all')   df.dropna(axis='columns')  NA的阈值。参数thresh=2,表示行/列中的NA数量大于2才删除
    2. 替换缺失值:fillna函数
	        设定每列NA的填充值。value为字典格式	
            values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
            df.fillna(value=values)
			生成字典
			   pd.isna(data) and isinstance(data, np.int64):
    3. 判断缺失值:isna函数
    4. 判断缺失值:notna函数
  缺失值在数据类型转换过程中的问题
      ValueError: cannot convert float NaN to integer

pandas展示

-- pandas在进行数据展示时,展示所有列
pd.set_option('display.max_columns', None)
pd.get_option('display.max_rows')
pd.get_option('display.max_columns')

重复值和异常值处理

 1.重复值:
   判断是否重复,
     and(df.duplicated())  any(df.duplicated(subset = ['price','cnt']))
   以及如何处理重复数据: 去重 合并
      去重:  drop_duplicats()
	  数keep
        keep可以为first和last,表示是选择最前一项还是最后一项保留,默认first,
		还有一个是 False   - False : Drop all duplicates.	    
 2.异常值
    异常值发现

向量化编程

  向量化编程
 1.Pandas中的apply
 2。向量化函数
    Numpy.vectorize()  或者使用Python装饰器 @np.vectorize
	使用库numba  numba.vectorize
 3.groupby
    grouped 对象  DataFrameGroupBy对象

字符串输出

拼接类:+、()、join()
     使用加号(+)连接,使用加号连接各个变量或者元素必须是字符串类型
插值类:f-string  <版本需要Python 3.6+>
   以字母f开头,在占位符中使用变量   
格式化类:%、format()、template
    format() :  占位符
    % : C printf格式化风格
      %s  %f

案例代码

  拼接SQL的数据
 `""" 数据示例
"st_date"	"scn_cd"	"state_score"	"state_cd"	"state_nm"	"state_type"	"state_day"
"20201101"	"1"	"5"	"00001"	"天织处"	"111"	"2020-11-22 11:22:31"
"20201101"	""	"0"	"00079"	"餐饮处"	""	"2020-11-22 11:22:32"
"20201101"	"1"	""	"00077"	""	"111"	"2020-11-22 11:22:33"
"20201101"	"2"	"0.3"	"00001"	"天织处"	"111"	""
"20201101"	"3"	"1.2"	"00001"	"天织处"	"TOTAL"	"2020-11-22 11:22:34"
"20201101"	"8"	"5.1"	"00078"	"小电局"	"ALL"	"2020-11-22 11:22:35"
"20201101"	"9"	"0.8"	"00001"	"天织处"	"111"	"2020-11-22 11:22:36"
"20201101"	"9"	"10"	"00006"	"浣乐处"	"111"	"2020-11-22 11:22:37"
"20201101"	"8"	"20"	"00005"	"百年处"	"111"	"2020-11-22 11:22:38"
"20201101"	"8"	"90"	"00004"	"杂货处"	"111"	"2020-11-22 11:22:39"
"""
#!/usr/bin/env python
# -*-coding:utf-8-*-
# @file read_data_create_test_data.py
# @date 2020-11-22

import pandas as pd

def concat_before_by_list(number) -> list:
""" 如果是字符串则不动,非字符串转为字符串,然后放到一个列表中"""
    paste_sql = []
    for i, data in enumerate(number):
        if isinstance(data, object):
            paste_sql.append(data)
       else:
            paste_sql.append('"'+str(data)+'"')
    return paste_sql


def concat_str_list(number) -> str:
""" 如果是字符串则不动,非字符串转为字符串,然后放到一个列表中"""
    return "select " + ",".join([str(x) for x in number]) + " union all"


def concat_str_list_2(data) -> str:
    """ 拼接字符串 """
    st_date, scn_cd = data[0], data[1]
    state_score, state_cd = data[2], data[3]
    state_nm, state_type,  = data[4], data[5]
    state_day = data[6]
    data = f'select  \'{st_date}\', {scn_cd} , {state_score}  , {state_cd} ' \
           f'\'{state_nm}\', {state_type} , {state_day}  union all '
    return data


if __name__ == '__main__':

"""1.input data输入数据 """
col_set_name = ["st_date", "scn_cd", "state_score", "state_cd",
                "state_nm", "state_type", "state_day"]
#  dtype:字典类型{'列名1':数据类型,‘列名’:数据类型} , dtype=object
col_type = {"st_date": str, "scn_cd": str, "state_score": str, "state_cd": str,
            "state_nm": str, "state_type": str, "state_day": str}
infile_name = r"C:\Users\df\Desktop\example_date.txt"
# header='infer'  None  read_csv 中关于缺失值的设定 na_values keep_default_na na_filter
orig_df = pd.read_table(infile_name, sep='\t', header=None, names=col_set_name,
                        skiprows=1, encoding='utf-8', dtype=col_type
                        )
"""2.查看数据并做数据类型的转换-数据预处理 """
print("##== Message:  2. 数据显示设置============================")
print(pd.get_option('display.max_rows'))
pd.set_option('display.max_columns', 7)
pd.set_option('display.max_colwidth', 20)
print(pd.get_option('display.max_columns'))
print(pd.get_option('display.precision'))
print("##== Message:  2.1 查看数据============================")
print(orig_df.head())
print(orig_df.shape)
# Numpy和Pandas的查看方式略有不同,一个是dtype,一个是dtypes
print(orig_df.dtypes)
print(orig_df.info)

print("##== Message:  2.2 数据类型转换============================")
# 没有缺失数据的情况可以用这个,有缺失值的时候 ValueError: cannot convert  NaN to integer
orig_df['st_date'] = orig_df['st_date'].astype('int64')
# The default return dtype is `float64` or `int64`  depending on the data supplied.
# coerce 遇到无法转化为数值的情况,转为Nan
orig_df['scn_cd'] = pd.to_numeric(orig_df['scn_cd'], errors="coerce", downcast='integer')
orig_df['state_score'] = pd.to_numeric(orig_df['state_score'], errors="coerce")
orig_df['state_day'] = pd.to_datetime(orig_df['state_day'])
orig_df['state_type'] = orig_df['state_type'].astype('category')

print("##== Message:  2.3 缺失值设定默认值============================")
"""缺失值的来源 1.数据集确实 2.数据整理过程确是 本例是数据集缺失的情况"""
"""缺失值的处理方式 1.替换自定义默认值 2.前值或后值填充  3.插值 4.删除. 本例使用1替换"""
# orig_df["state_type"] 返回 Series pd.Categorical 来构建分类数据 ,增加默认值的类型
# orig_df["state_type"] = pd.Categorical(orig_df["state_type"], categories=['111', 'ALL', 'TOTAL', "DEFat"])
# print(orig_df["state_type"].cat.categories)
# fill value must be in categories 插值必须在类型中,在这里添加类型,以方便后续插入

orig_df['state_type'] = orig_df["state_type"].cat.add_categories("DEFat")
values_fill = {"st_date": '20201101', "scn_cd": 0, "state_score": 0.0, "state_cd": "FILLDa",
                         "state_nm": "FILLNm", "state_type": "DEFat",
               "state_day": pd.to_datetime("2020-11-22 22:22:22")}
# 转换过来,以上只是用来演示转换时间
orig_df['state_day'] = orig_df['state_day'].astype('str')

deal_df = orig_df.fillna(value=values_fill)
deal_df['scn_cd'] = deal_df['scn_cd'].astype('int')
orig_df['state_cd'] = orig_df['state_cd'].astype('int64')
print(orig_df['state_cd'].astype('int64'))
print(deal_df.info)
print(deal_df.describe())
print(deal_df.dtypes)
# 使用loc获取列子集-使用带逗号的方括号 返回的是DF
print(deal_df.loc[:, ["state_type"]])
# 返回 Series [] 是列表, 单个值 deal_df[["state_type"]] 和 deal_df["state_type"] 之间返回值不同
print(deal_df["state_type"].cat.categories)

print("##== Message:  2.2 数据向量化处理============================")
# 方式一 使用 apply
dataDF = deal_df.apply(concat_before_by_list, axis=1)
pd.set_option('display.max_colwidth', 200)
print(dataDF)
# 方式二 函数向量化
tt = dataDF.apply(concat_str_list, axis=1)

# 方式 apply函数结合group by的使用
# agg aggregate
# filter
# transform  类似于Spark中的 map SparkSQL中的 udf
# split apply combine

print("##== Message:  3 输出 ============================")
dataDF.to_csv('C:/Users/df/Desktop/t_sroom_de_m.txt',
           sep='\t', header=False, quoting=0, index=False)

`

参考:

  https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
posted @ 2020-11-25 12:45  辰令  阅读(338)  评论(0编辑  收藏  举报