zoukankan      html  css  js  c++  java
  • 基于pandas进行数据预处理

    很久没用pandas,有些有点忘了,转载一个比较完整的利用pandas进行数据预处理的博文:https://blog.csdn.net/u014400239/article/details/70846634

    引入包和加载数据

    1 import pandas as pd
    2 import numpy as np
    3 train_df =pd.read_csv('../datas/train.csv')  # train set
    4 test_df  = pd.read_csv('../datas/test.csv')   # test  set
    5 combine  = [train_df, test_df]
     

    清洗数据

    • 查看数据维度以及类型
    • 缺失值处理
    • 查看object数据统计信息
    • 数值属性离散化
    • 计算特征与target属性之间关系

    查看数据维度以及类型

    1 #查看前五条数据
    2 print train_df.head(5)  
    3 #查看每列数据类型以及nan情况
    4 print train_df.info()  
    5 # 获得所有object属性
    6 print train_data.describe().columns 

    查看object数据统计信息

    1 #查看连续数值属性基本统计情况
    2 print train_df.describe()  
    3 #查看object属性数据统计情况
    4 print train_df.describe(include=['O'])  
    5 # 统计Title单列各个元素对应的个数
    6 print train_df['Title'].value_counts() 
    7 # 属性列删除
    8 train_df = train_df.drop(['Name', 'PassengerId'], axis=0)  

    Ps.原文中axis的处理是不对的,Python中axis = 0是按列处理,axis = 1 是按行处理

    缺失值处理

     1 # 直接丢弃缺失数据列的行
     2 print df4.dropna(axis=1,subset=['col1'])  # 丢弃nan的行,subset指定查看哪几列 
     3 print df4.dropna(axis=0)  # 丢弃nan的列
     4 # 采用其他值填充
     5 dataset['Cabin'] = dataset['Cabin'].fillna('U') 
     6 dataset['Title'] = dataset['Title'].fillna(0) 
     7 # 采用出现最频繁的值填充
     8 freq_port = train_df.Embarked.dropna().mode()[0]
     9 dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
    10 # 采用中位数或者平均数填充
    11 test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
    12 test_df['Fare'].fillna(test_df['Fare'].dropna().mean(), inplace=True)

    数值属性离散化,object属性数值化

    1 # 创造一个新列,FareBand,将连续属性Fare切分成四份
    2 train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)
    3 # 查看切分后的属性与target属性Survive的关系
    4 train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)
    5 # 建立object属性映射字典  
    6 title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Royalty":5, "Officer": 6}
    7 dataset['Title'] = dataset['Title'].map(title_mapping)
    
    

    计算特征与target属性之间关系

    • object与连续target属性之间,可以groupby均值
    • object与离散target属性之间,先将target数值化,然后groupby均值,或者分别条形统计图
    • 连续属性需要先切割然后再进行groupby计算,或者pearson相关系数
    1 print train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)

    总结pandas基本操作

     1 ”’ 
     2 创建df对象 
     3 ””’ 
     4 s1 = pd.Series([1,2,3,np.nan,4,5]) 
     5 s2 = pd.Series([np.nan,1,2,3,4,5]) 
     6 print s1 
     7 dates = pd.date_range(“20130101”,periods=6) 
     8 print dates 
     9 df = pd.DataFrame(np.random.rand(6,4),index=dates,columns=list(“ABCD”)) 
    10 # print df 
    11 df2 = pd.DataFrame({“A”:1, 
    12 ‘B’:pd.Timestamp(‘20130102’), 
    13 ‘C’:pd.Series(1,index=list(range(4)),dtype=’float32’), 
    14 ‘D’:np.array([3]*4,dtype=np.int32), 
    15 ‘E’:pd.Categorical([‘test’,’train’,’test’,’train’]), 
    16 ‘F’:’foo’ 
    17 }) 
    18 # print df2.dtypes
    19 
    20 df3 = pd.DataFrame({'col1':s1,
    21                     'col2':s2
    22 })
    23 print df3
    24 
    25 '''
    26 2.查看df数据
    27 '''
    28 print df3.head(2) #查看头几条
    29 print df3.tail(3) #查看尾几条
    30 print df.index  #查看索引
    31 print df.info()  #查看非non数据条数
    32 print type(df.values)  #返回二元数组
    33 # print df3.values
    34 print df.describe()   #对每列数据进行初步的统计
    35 print df3
    36 print df3.sort_values(by=['col1'],axis=0,ascending=True) #按照哪几列排序
    37 
    38 '''
    39 3.选择数据
    40 '''
    41 ser_1 = df3['col1']
    42 print type(ser_1) #pandas.core.series.Series
    43 print df3[0:2] #前三行
    44 print df3.loc[df3.index[0]]  #通过index来访问
    45 print df3.loc[df3.index[0],['col2']]  #通过行index,和列名来唯一确定一个位置
    46 print df3.iloc[1] #通过位置来访问
    47 print df3.iloc[[1,2],1:2] #通过位置来访问
    48 print "==="
    49 print df3.loc[:,['col1','col2']].as_matrix()   # 返回nunpy二元数组
    50 print type(df3.loc[:,['col1','col2']].as_matrix())
    51 
    52 '''
    53 4.布尔索引,过滤数据
    54 '''
    55 print df3[df3.col1 >2]
    56 df4 = df3.copy()
    57 df4['col3']=pd.Series(['one','two','two','three','one','two'])
    58 print df4
    59 print df4[df4['col3'].isin(['one','two'])]
    60 df4.loc[:,'col3']="five"
    61 print df4
    62 
    63 '''
    64 5.缺失值处理,pandas将缺失值用nan代替
    65 '''
    66 print pd.isnull(df4)
    67 print df4.dropna(axis=0,subset=['col1'])  # 丢弃nan的行,subset指定查看哪几列
    68 print df4.dropna(axis=1)  # 丢弃nan的列
  • 相关阅读:
    cookie操作和代理
    发起post请求
    scrapy核心组件
    爬取多个url页面数据--手动实现
    scrapy之持久化存储
    selenium + phantomJs
    scrapy框架简介和基础使用
    校验验证码 实现登录验证
    beautifulsoup解析
    xpath
  • 原文地址:https://www.cnblogs.com/VanJing/p/9356351.html
Copyright © 2011-2022 走看看