Skip to the content.

04-数据预处理


创建数据案例

import pandas as pd
import numpy as np
df = pd.DataFrame({'id':[1001,1002,1003,1004,1005,1006], 
                   'date':pd.date_range('20130102', periods=6),
                   'city':['Beijing','SH','Guangzhou ','Shenzhen','Shanghai', 'Beijing'],
                   'age':[23,44,54,32,34,32],
                   'category':['100-A','100-B','110-A','110-C','210-A','130-F'],
                   'price':[1200,np.nan,2133,5433,np.nan,4432]},
                   columns =['id','date','city','category','age','price'])



数据索引

# 设置索引
df.set_index('id')

# 重置索引
df.reset_index() 
df.reset_index(drop=True) #不保留原索引列

# 使用索引进行数据表关联
df = pd.merge(df1, df2, left_index = True, right_index= True)



数据排序

# 按特定列的值排序
df.sort_values(by=['age'])

# 按多列的数值进行排序
df.sort_values(by=['age', 'price'], ascending= [True, False])

# 按索引列排序
df.sort_index()

# 新增排序编号列
df['index'] = range(len(df))

# 对某列排序并编号
df['rank'] = df['age'].rank(method = 'first').apply(lambda x: int(x))



数据重组

# 堆叠(将矩阵数据转为列表)
df.stack()
df.unstack()

# 将id作为行,date作为列。将数组转置
df2 = df.pivot('id','date').swaplevel(axis=1).stack()
df2.reset_index(inplace=True)

# 将某列排到第一列
df3 = df[['age'] + df.columns.drop('age').tolist()]

# 将所有行反转
df.loc[::-1].reset_index(drop=True)

# 将所有列反转
df.loc[:, ::-1]

# 根据序号重排列
cols = df.columns[[3,2,1,0]]
df_new = df[cols]



数据衍生

生成标签与分列

# 依据数值生成标签
# 如果price列的值>3000,group列显示high,否则显示low
df['group'] = np.where(df['price'] > 3000, 'high', 'low')

# 对复合多个条件的数据进行分组标记
df['sign'] = 0
df.loc[(df['city'] == 'beijing') & (df['price'] >= 4000), 'sign'] = 1

# 跨列判断
df['province_match'] = df.apply(lambda x: x.province1.lower() == x.province2.lower(),axis=1)
df['province_match'] = df['province_match'].astype('int')

# 数据分列与合并
# 根据特殊符号、位置分列
df['first_cat'] = df['category'].str.split('-', n=1).str[0]
df['last_cat'] = df['category'].str.split('-', n=1).str[1]

# 对category字段的值依次进行分列,列名称为category和size
pd.DataFrame((x.split('-') for x in df['category']), index=df.index,columns=['category','size'])

# 用特殊符号对列进行合并
df['category_2'] = df['first_cat'].str.cat(df['last_cat'], sep = '*')
df['category_2'] = df['first_cat'] + '*' +df['last_cat']

# 统计特殊符号的个数
df['cnt'] = df['reports'].apply(lambda x: x.count('|')

# 根据不同的判断条件,选取不同列的数值
df = pd.DataFrame([
        ['qwe', 'a', 3, 4.5, 0.0],
        ['qwe', 'a', 6, 8.0, 0.0],
        ['asd', 'b', 3, 0.0, 4.5],
        ['asd', 'b',12, 0.0, 12.0],
        ['zxc', 'c', 6, 8.0, 2.0],
        ['zxc', 'c',12,12.0, 3.0]],
        columns=['name', 'type', 'period', 'fee_A', 'fee_B'])

tp = df.set_index(['name', 'period'])
tp1= tp.apply(lambda x: x.fee_A if x.type == 'a'
              else (x.fee_B if x.type == 'b'
              else (x.fee_A + x.fee_B)), axis=1)
res = tp1.unstack()


分箱与哑变量

# 随机生成1000个0-1之间的小数
import numpy as np
np.random.seed(123)
values = np.random.rand(1000)

# 按阈值分箱
bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
pd.cut(values, bins).value_counts()

# 对分箱结果转为哑变量
pd.get_dummies(pd.cut(values, bins))

# 按分位数分箱
pd.qcut(values, 4).value_counts()

# 对数据表中所有文本变量转为哑变量
df_num = pd.get_dummies(df, df.loc[:,df.dtypes == 'O'].columns)


< <目录 05-数据筛选 > 返回顶部 ↑