zoukankan      html  css  js  c++  java
  • Kaggle-pandas(4)

    Grouping-and-sorting

    教程

    映射使我们可以一次将整个列中的数据转换为DataFrame或Series中的一个值。 但是,通常我们希望对数据进行分组,然后对数据所在的组进行特定的操作。
    正如您将学到的,我们使用groupby()操作来完成此操作。 我们还将介绍一些其他主题,例如为DataFrames编制索引的更复杂方法以及如何对数据进行排序。

    Groupwise analysis

    到目前为止,我们一直在使用的一个函数是value_counts()函数。 我们可以通过执行以下操作来复制value_counts()的功能:

    reviews.groupby('points').points.count()

    groupby()创建了一组reviews,这些reviews为给定的葡萄酒分配了相同的分值。 然后,对于每个组,我们都抓住了points()列并计算了它出现的次数。 value_counts()只是该groupby()操作的快捷方式。
    我们可以将之前使用的任何汇总功能与此数据一起使用。 例如,要获取每个点值类别中最便宜的葡萄酒,我们可以执行以下操作:

    reviews.groupby('points').price.min()

    您可以将我们生成的每个组视为DataFrame的一部分,其中仅包含具有匹配值的数据。 我们可以使用apply()方法直接访问此DataFrame,然后我们可以按照自己认为合适的任何方式来操作数据。 例如,这是一种从数据集中的每个酿酒厂中选择第一批葡萄酒名称的方法:

    reviews.groupby('winery').apply(lambda df: df.title.iloc[0])

    为了获得更细粒度的控制,您还可以按多个列进行分组。 例如,以下是我们如何按国家和省份挑选最佳葡萄酒的方法:

    reviews.groupby(['country', 'province']).apply(lambda df: df.loc[df.points.idxmax()])

    分类结果如下

    另一个值得一提的groupby()方法是agg(),它使您可以同时在DataFrame上运行许多不同的函数。 例如,我们可以生成数据集的简单统计摘要,如下所示:

    reviews.groupby(['country']).price.agg([len, min, max])

     Multi-indexes

    到目前为止,在所有示例中,我们一直在使用带有单标签索引的DataFrame或Series对象。 groupby()稍有不同,因为它取决于我们运行的操作,有时会导致所谓的多索引。
    多索引与常规索引的不同之处在于它具有多个级别。 例如:

    countries_reviewed = reviews.groupby(['country', 'province']).description.agg([len])
    countries_reviewed

    mi = countries_reviewed.index
    type(mi)

    Output:

    pandas.core.indexes.multi.MultiIndex

    多索引有几种方法来处理它们的分层结构,而单级索引则没有。 它们还需要两个级别的标签才能检索值。 对于刚接触pandas的用户来说,处理多索引输出是常见的“陷阱”。
    pandas文档的“多索引/高级选择”部分中详细说明了多索引的使用案例以及使用说明。

    但是,通常,您最常使用的多索引方法是一种可转换回常规索引的方法,即reset_index()方法:

     Sorting

    再次查看countries_reviewed,我们可以看到分组以索引顺序而不是以值顺序返回数据。 也就是说,在输出groupby的结果时,行的顺序取决于索引中的值,而不取决于数据中的值。
    要按需要的顺序获取数据,我们可以自己对其进行排序。 sort_values()方法很方便。

    countries_reviewed = countries_reviewed.reset_index()
    countries_reviewed.sort_values(by='len')

    Output:

    要按索引值排序,请使用配套方法sort_index()。 此方法具有相同的参数和默认顺序:

    countries_reviewed.sort_index()

    Output:

    练习

    1

    Who are the most common wine reviewers in the dataset? Create a Series whose index is the taster_twitter_handle category from the dataset, and whose values count how many reviews each person wrote.

    # Your code here
    reviews_written = reviews.groupby("taster_twitter_handle").taster_twitter_handle.count()
    print(reviews_written)
    
    # Check your answer
    q1.check()

    2.

    What is the best wine I can buy for a given amount of money? Create a Series whose index is wine prices and whose values is the maximum number of points a wine costing that much was given in a review. Sort the values by price, ascending (so that 4.0 dollars is at the top and 3300.0 dollars is at the bottom).

    best_rating_per_price = reviews.groupby('price')['points'].max().sort_index()
    # Check your answer
    q2.check()

    3.

    What are the minimum and maximum prices for each variety of wine? Create a DataFrame whose index is the variety category from the dataset and whose values are the min and max values thereof.

    price_extremes = reviews.groupby('variety')["price"].agg([min,max])
    
    # Check your answer
    q3.check()

    4.

    What are the most expensive wine varieties? Create a variable sorted_varieties containing a copy of the dataframe from the previous question where varieties are sorted in descending order based on minimum price, then on maximum price (to break ties).

    sorted_varieties = price_extremes.sort_values(by=['min', 'max'], ascending=False)
    # Check your answer
    q4.check()

    5.

    Create a Series whose index is reviewers and whose values is the average review score given out by that reviewer. Hint: you will need the taster_name and points columns.

    reviewer_mean_ratings = reviews.groupby('taster_name').points.mean()
    
    # Check your answer
    q5.check()

    6.

    What combination of countries and varieties are most common? Create a Series whose index is a MultiIndexof {country, variety} pairs. For example, a pinot noir produced in the US should map to {"US", "Pinot Noir"}. Sort the values in the Series in descending order based on wine count.

    country_variety_counts = reviews.groupby(['country', 'variety']).size().sort_values(ascending=False)
    
    # Check your answer
    q6.check()
  • 相关阅读:
    网桥的作用
    PMML辅助机器学习算法上线
    支持度、置信度和提升度
    特征预处理
    特征表达及处理
    卡方检验
    特征工程-特征选择
    AMBARI部署HADOOP集群(4)
    AMBARI部署HADOOP集群(3)
    ambari部署Hadoop集群(2)
  • 原文地址:https://www.cnblogs.com/caishunzhe/p/13429719.html
Copyright © 2011-2022 走看看