pandas快速入门(2):预处理

2018-09-02  本文已影响0人  大锅烩菜

1. 基本运算

info = pandas.read_csv("food_info.csv")
print(info["Iron_(mg)"].head(5))

add_10 = info["Iron_(mg)"] + 10
print(add_10.head(5))
div_10 = add_10 /10
print(div_10.head(5))

结果:


2. 排序

info = pandas.read_csv("food_info.csv")
print(info["Sodium_(mg)"].head(5))
# inplace=True:不创建新的对象,直接对原始对象进行修改;
info.sort_values("Sodium_(mg)",inplace=True)
print(info["Sodium_(mg)"].head(5))

默认是升序,降序使用方法:

info = pandas.read_csv("food_info.csv")
print(info["Sodium_(mg)"].head(5))
# ascending=False 是降序
info.sort_values("Sodium_(mg)",inplace=True,ascending=False)
print(info["Sodium_(mg)"].head(5))

3. 空值判断与统计

tt = pandas.read_csv("titanic_train.csv")
age = tt["Age"]
print(age.loc[0:6])
# 判断每个值是否为空
age_is_null = pandas.isnull(age)
# 获取值为空的行
null_values = age[age_is_null].loc[0:6]
print(null_values)
# 统计空值的数量
null_count = len(age_is_null)
print(null_count)

4. 统计平均值

当数据有空值时,统计方法如下:

tt = pandas.read_csv("titanic_train.csv")
age_is_null = pandas.isnull(tt["Age"])
# 将不为空的找到
valid_age = tt["Age"][age_is_null==False]
## 4. 平均值
avg_age = sum(valid_age) /len(valid_age)
print(avg_age)

更简单的是使用mean函数,会自动刨除空值行

tt = pandas.read_csv("titanic_train.csv")
avg_age = tt["Age"].mean()
print(avg_age)

5. 分类统计概率

按照船票级别统计票件

tt = pandas.read_csv("titanic_train.csv")
# 船票等级列表
passenger_classes = [1,2,3]
# 字典用于存储各等级对应的平均票价格
fares_by_classes = {}
for cls in passenger_classes:
    # 获取某一等级的所有记录
    pcls_row = tt[tt["Pclass"]==cls]
    pcls_fares = pcls_row["Fare"]
    fare_for_class = pcls_fares.mean()
    fares_by_classes[cls] = fare_for_class
print(fares_by_classes)

更简单是使用pivot_table函数:

import numpy,pandas
tt = pandas.read_csv("titanic_train.csv")
# index 是按照那一列进行分类。values是进行统计的列。aggfunc是对分类中所有列使用的统计函数
fares_by_classes = tt.pivot_table(index="Pclass",values="Fare",aggfunc=numpy.mean)
print(fares_by_classes)

案例:统计不同等级船票的存活率

import numpy,pandas
tt = pandas.read_csv("titanic_train.csv")
survived_by_class = tt.pivot_table(index="Pclass",values="Survived",aggfunc=numpy.mean)
print(survived_by_class)

pivot_table还可以分类统计多列。例如,统计不同登机地点的人数的存活人数与船票总数

import numpy,pandas
tt = pandas.read_csv("titanic_train.csv")
survived_by_class = tt.pivot_table(index="Embarked",values=["Fare","Survived"],aggfunc=numpy.sum)
print(survived_by_class)

6. 筛选样本

dropna函数可以将有空值的样本去除掉

tt = pandas.read_csv("titanic_train.csv")
# axis=1或者axis="columns"将会去掉有null值的列
res = tt.dropna(axis=1)
# subset 表示去掉该集合中的所有列,其他列的空值不去掉
res_2 = tt.dropna(axis=0,subset=["Age","Sex"])
print(res_2.loc[0:6])

7. 定位样本

查看第11号样本的age属性的值

tt = pandas.read_csv("titanic_train.csv")
print(tt.loc[10,"Age"])

8. 重设索引

排序后,索引顺序会混乱,如下:

tt = pandas.read_csv("titanic_train.csv")
tt = tt.sort_values("Age")
print(tt.head(5))

结果:



可以用下面的方式重建索引,使排列有序:

print(tt.head(5))
# 重建索引  drop=True,则表示完全重建索引,False则会在原来数据中添加index列,并将原索引插入
tt_reindexed =tt.reset_index(drop=True)
print(tt_reindexed.head(5))

结果:


9. apply函数调用函数

输出100号样本的内容

def hundr_row(sample):
    hunder_item = sample.loc[99]
    return hunder_item
# 调用自定义函数
h_r = tt.apply(hundr_row)
print(h_r)

输出所有列空值的数量

# 判断空值的数量
def not_null_count(sample):
    column_null = pandas.isnull(sample)
    null = sample[column_null]
    return len(null)
tt = pandas.read_csv("titanic_train.csv")
column_null_count = tt.apply(not_null_count)
print(column_null_count)

判断每条记录所属的船舱等级:

def which_class(sample):
    pclass = sample["Pclass"]
    if pandas.isnull(pclass):
        return "Unknown"
    elif pclass == 1:
        return "First class"
    elif pclass == 2:
        return "Second class"
    elif pclass == 3:
        return "Third class"
# axis =1 表示apply在每一行行上调用which_class函数
classes = tt.apply(which_class,axis =1)
print(classes)

判断是否成年

def is_minor(row):
    if row["Age"] <18:
        return True
    else:
        return False
is_minor = tt.apply(is_minor,axis=1)
print(is_minor)

判断不同年龄阶段的存活率

def get_age_label(sample):
    age = sample["Age"]
    if pandas.isnull(age):
        return "Unknown"
    elif age <18:
        return "minor"
    else:
        return "adult"
label = tt.apply(get_age_label,axis=1)

#添加label列
tt["label"] = label
# 根据年龄阶段统计存活率
age_survived  = tt.pivot_table(index="label",values="Survived")  
print(age_survived)
上一篇 下一篇

猜你喜欢

热点阅读