• pandas 常用函数


    一、常用功能及函数简介

    包导入

    一般我们需要做如下导入,numpy和pandas一般需要联合使用:

    import pandas as pd
    import numpy as np
    本文采用如下缩写:

    df:Pandas DataFrame对象
    s:  Pandas Series对象
    数据导入

    pd.read_csv(filename):从CSV文件导入数据
    pd.read_table(filename):从限定分隔符的文本文件导入数据
    pd.read_excel(filename):从Excel文件导入数据
    pd.read_sql(query, connection_object):从SQL表/库导入数据
    pd.read_json(json_string):从JSON格式的字符串导入数据
    pd.read_html(url):解析URL、字符串或者HTML文件
    pd.read_clipboard():从粘贴板获取内容
    pd.DataFrame(dict):从字典对象导入数据
    数据导出

    df.to_csv(filename):导出数据到CSV文件
    df.to_excel(filename):导出数据到Excel文件
    df.to_sql(table_name, connection_object):导出数据到SQL表
    df.to_json(filename):以Json格式导出数据到文本文件
    创建对象

    pd.DataFrame(np.random.rand(20,5)):创建20行5列的随机数组成的DataFrame对象
    pd.Series(my_list):从可迭代对象my_list创建一个Series对象
    df.index = pd.date_range('1900/1/30', periods=df.shape[0]):增加一个日期索引
    index和reindex联合使用很有用处,index可作为索引并且元素乱排序之后,所以跟着元素保持不变,因此,当重拍元素时,只需要对index进行才重排即可:reindex。

    另外, reindex时,还可以增加新的标为NaN的元素。

    数据查看

    df.head(n):查看DataFrame对象的前n行
    df.tail(n):查看DataFrame对象的最后n行
    df.shape():查看行数和列数
    df.info():查看索引、数据类型和内存信息
    df.describe():查看数值型列的汇总统计
    s.value_counts(dropna=False):查看Series对象的唯一值和计数
    df.apply(pd.Series.value_counts):查看DataFrame对象中每一列的唯一值和计数
    apply的用处很多,比如可以通过跟lambda函数联合,完成很多功能:将包含某个部分的元素挑出来等等。

    cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San'))

     
    数据选取

    df[col]:根据列名,并以Series的形式返回列
    df[[col1, col2]]:以DataFrame形式返回多列
    s.iloc[0]:按位置选取数据
    s.loc['index_one']:按索引选取数据
    df.iloc[0,:]:返回第一行
    数据清洗

    df.columns = ['a','b','c']:重命名列名
    pd.isnull():检查DataFrame对象中的空值,并返回一个Boolean数组
    pd.notnull():检查DataFrame对象中的非空值,并返回一个Boolean数组
    df.dropna():删除所有包含空值的行
    df.fillna(x):用x替换DataFrame对象中所有的空值
    s.astype(float):将Series中的数据类型更改为float类型
    s.replace(1,'one'):用‘one’代替所有等于1的值
    df.rename(columns=lambda x: x + 1):批量更改列名
    df.set_index('column_one'):更改索引列
    数据处理:Filter, Sort, GroupBy

    df[df[col] > 0.5]:选择col列的值大于0.5的行
    df.sort_values(col1):按照列col1排序数据,默认升序排列
    df.groupby(col):返回一个按列col进行分组的Groupby对象
    df.groupby(col1).agg(np.mean):返回按列col1分组的所有列的均值
    df.pivot_table(index=col1, values=[col2,col3], aggfunc=max):创建一个按列col1进行分组,并计算col2和col3的最大值的数据透视表
    data.apply(np.mean):对DataFrame中的每一列应用函数np.mean
    数据合并

    df1.append(df2):将df2中的行添加到df1的尾部
    df.concat([df1, df2],axis=1):将df2中的列添加到df1的尾部
    df1.join(df2,on=col1,how='inner'):对df1的列和df2的列执行SQL形式的join
    数据统计

    df.describe():查看数据值列的汇总统计
    df.mean():返回所有列的均值
    df.corr():返回列与列之间的相关系数
    df.count():返回每一列中的非空值的个数
    df.max():返回每一列的最大值
    df.min():返回每一列的最小值
    df.median():返回每一列的中位数
    df.std():返回每一列的标准差
    Pandas支持的数据类型

    int 整型
    float 浮点型
    bool 布尔类型
    object 字符串类型
    category 种类
    datetime 时间类型
    补充:

    df.astypes: 数据格式转换
    df.value_counts:相同数值的个数统计
    df.hist(): 画直方图
    df.get_dummies: one-hot编码,将类型格式的属性转换成矩阵型的属性。比如:三种颜色RGB,红色编码为[1 0 0]
     

    参考文章:

    Pandas官网

    Pandas官方文档

    Pandas Cheat Sheet -- Python for Data Science

    10 minutes to Pandas

    二、房价预测案例

    根据给定的训练csv文件,预测给出的测试csv文件中的房价。


     
    import numpy as np
    import pandas as pd
    from Cython.Shadow import inline
     
    import matplotlib.pyplot as plt
    #matplotlib inline
     
    ###################1 oridinal data##################
    train_df = pd.read_csv('input/train.csv', index_col=0)#数据导入
    test_df = pd.read_csv('input/test.csv', index_col=0)
     
    print("type of train_df:" + str(type(train_df)))
    #print(train_df.columns)
    print("shape of train_df:" + str(train_df.shape))
    print("shape of test_df:" + str(test_df.shape))
     
    train_df.head()#数据查看
    #print(train_df.head())
     
    ###################2 smooth label######################
    prices = pd.DataFrame({"price":train_df["SalePrice"], "log(price+1)":np.log1p(train_df["SalePrice"])})
    print("shape of prices:" + str(prices.shape))#数据创建
    prices.hist()#直方图
    # plt.plot(alphas, test_scores)
    # plt.title("Alpha vs CV Error")
    plt.show()
     
    y_train = np.log1p(train_df.pop('SalePrice'))
    print("shape of y_train:" + str(y_train.shape))
     
    ###################3 take train and test data together##############
    all_df = pd.concat((train_df, test_df), axis=0)#数据合并
    print("shape of all_df:" + str(all_df.shape))
     
    ###################4 make category data to string####################
    print(all_df['MSSubClass'].dtypes)
    all_df['MSSubClass'] = all_df['MSSubClass'].astype(str)#数据格式转换
    all_df['MSSubClass'].value_counts()#相同数值个数统计
    print(all_df['MSSubClass'].value_counts())
     
    ##################5 fill null###########################
    all_dummy_df = pd.get_dummies(all_df)#one-hot编码,颜色RGB,则R编码为[1 0 0]
    print(all_dummy_df.head())#下一行进行数据清洗,找到为空的属性,并按照空的数量对属性排序
    print(all_dummy_df.isnull().sum().sort_values(ascending=False).head())
     
    mean_cols = all_dummy_df.mean()#数据统计,均值
    print(mean_cols.head(10))
     
    all_dummy_df = all_dummy_df.fillna(mean_cols)#数据清洗,用()中的值代替空值
    print(all_dummy_df.isnull().sum().sum())
     
    ###############6 smooth numeric cols########################
    numeric_cols = all_df.columns[all_df.dtypes != 'object']#选取属性不是object,即数值型数据
    print(numeric_cols)
     
    numeric_col_means = all_dummy_df.loc[:, numeric_cols].mean()#按照括号的索引选取数据,并求均值
    numeric_col_std = all_dummy_df.loc[:, numeric_cols].std()
    all_dummy_df.loc[:, numeric_cols] = (all_dummy_df.loc[:, numeric_cols] - numeric_col_means) / numeric_col_std
     
    ###############7 train model#######################
    dummy_train_df = all_dummy_df.loc[train_df.index]
    dummy_test_df = all_dummy_df.loc[test_df.index]
    print("shape of dummy_train_df:" + str(dummy_train_df))
    print("shape of dummy_test_df:" + str(dummy_test_df))
     
    from sklearn.linear_model import Ridge
    from sklearn.model_selection import cross_val_score
     
    X_train = dummy_train_df.values
    X_test = dummy_test_df.values
     
    alphas = np.logspace(-3, 2, 50)
    test_scores = []
    for alpha in alphas:
    clf = Ridge(alpha)
    test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=10, scoring='neg_mean_squared_error'))
    test_scores.append(np.mean(test_score))
    plt.plot(alphas, test_scores)
    plt.title("Alpha vs CV Error")
    plt.show()
     
    from sklearn.ensemble import RandomForestRegressor
    max_features = [.1, .3, .5, .7, .9, .99]
    test_scores = []
    for max_feat in max_features:
    clf = RandomForestRegressor(n_estimators=200, max_features=max_feat)
    test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=5, scoring='neg_mean_squared_error'))
    test_scores.append(np.mean(test_score))
     
    plt.plot(max_features, test_scores)
    plt.title("Max Features vs CV Error")
    plt.show()
     
    #########################8 stacking#####################
    ridge = Ridge(alpha=15)
    rf = RandomForestRegressor(n_estimators=200, max_features=.3)
    ridge.fit(X_train, y_train)
    rf.fit(X_train, y_train)
     
    y_ridge = np.expm1(ridge.predict(X_test))
    y_rf = np.expm1(rf.predict(X_test))
     
    y_final = (y_ridge + y_rf)/2
     
    ######################9 submission############################
    submission_df = pd.DataFrame(data = {'Id':test_df.index, 'SalePrice':y_final})
    print(submission_df.head())

  • 相关阅读:
    Android消息队列模型——Thread,Handler,Looper,Massage Queue
    源代码管理十诫
    他们怎样读书和选书(汇总篇)
    Android消息处理机制
    互联网上的免费服务都是怎么赚钱的
    编程是一种对你的身体健康十分有害的工作
    ERROR/AndroidRuntime(716): java.lang.SecurityException: Binder invocation to an incorrect interface
    什么是 MIME Type?
    TCP/IP:网络因此互联
    Eclipse上GIT插件EGIT使用手册
  • 原文地址:https://www.cnblogs.com/aibabel/p/11011614.html
Copyright © 2020-2023  润新知