pandas 数据归一化以及行删除例程的方法

如下所示:

#coding:utf8

import pandas as pd

import numpy as np

from pandas import Series,DataFrame

# 如果有id列,则需先删除id列再进行对应操作,最后再补上

# 统计的时候不需要用到id列,删除的时候需要考虑

# delete row

def row_del(df, num_percent, label_len = 0):

#print list(df.count(axis=1))

col_num = len(list(list(df.values)[1])) - label_len # -1为考虑带标签

if col_num<0:

print 'Error'

#print int(col_num*num_percent)

return df.dropna(axis=0, how='any', thresh=int(col_num*num_percent))

# 如果有字符串类型,则报错

# data normalization -1 to 1

# label_col: 不需考虑的类标,可以为字符串或字符串列表

# 数值类型统一到float64

def data_normalization(df, label_col = []):

lab_len = len(label_col)

print label_col

if lab_len>0:

df_temp = df.drop(label_col, axis = 1)

df_lab = df[label_col]

print df_lab

else:

df_temp = df

max_val = list(df_temp.max(axis=0))

min_val = list(df_temp.min(axis=0))

mean_val = list((df_temp.max(axis=0) + df_temp.min(axis=0)) / 2)

nan_values = df_temp.isnull().values

row_num = len(list(df_temp.values))

col_num = len(list(df_temp.values)[1])

for rn in range(row_num):

#data_values_r = list(data_values[rn])

nan_values_r = list(nan_values[rn])

for cn in range(col_num):

if nan_values_r[cn] == False:

df_temp.values[rn][cn] = 2 * (df_temp.values[rn][cn] - mean_val[cn])/(max_val[cn] - min_val[cn])

else:

print 'Wrong'

for index,lab in enumerate(label_col):

df_temp.insert(index, lab, df_lab[lab])

return df_temp

# 创建一个带有缺失值的数据框:

df = pd.DataFrame(np.random.randn(5,3), index=list('abcde'), columns=['one','two','three'])

df.ix[1,:-1]=np.nan

df.ix[1:-1,2]=np.nan

df.ix[0,0]=int(1)

df.ix[2,2]='abc'

# 查看一下数据内容:

print '\ndf1'

print df

print row_del(df, 0.8)

print '-------------------------'

df = data_normalization(df, ['two', 'three'])

print df

print df.dtypes

print (type(df.ix[2,2]))

以上这篇pandas 数据归一化以及行删除例程的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

以上是 pandas 数据归一化以及行删除例程的方法 的全部内容, 来源链接: utcz.com/z/349619.html

回到顶部