Kaggle-pandas(3)


Summary-functions-and-maps

教程

在上一教程中,我們學習了如何從DataFrame或Series中選擇相關數據。 正如我們在練習中所展示的,從我們的數據表示中提取正確的數據對於完成工作至關重要。
但是,數據並非總是以我們想要的格式從內存中出來的。 有時,我們必須自己做一些工作以將其重新格式化以解決當前的任務。 本教程將介紹我們可以應用於數據以獲取“恰到好處”輸入的各種操作。

Pandas提供了許多簡單的“摘要功能”(不是官方名稱),它們以某種有用的方式重組了數據。 例如,考慮一下describe()方法:

reviews.points.describe()

Output:

此方法生成給定列的屬性的高級摘要。 它可識別類型,這意味着其輸出根據輸入的數據類型而變化。 上面的輸出僅對數字數據有意義; 對於字符串數據,這是我們得到的:

 

 

 如果要獲取有關DataFrame或Series中某一列的某些特定的簡單摘要統計信息,通常有一個有用的pandas函數可以實現此目的。
例如,要查看分配的分數的平均值(例如,平均評級的葡萄酒表現如何),我們可以使用mean()函數:

reviews.points.mean()

要查看唯一值的列表,我們可以使用unique()函數:

reviews.taster_name.unique()

要查看唯一值的列表以及它們在數據集中出現的頻率,我們可以使用value_counts()方法:

reviews.taster_name.value_counts()

Maps

 映射是一個從數學中借來的術語,表示一個函數,該函數采用一組值並將它們“映射”到另一組值。 在數據科學中,我們經常需要根據現有數據創建新的表示形式,或者將數據從現在的格式轉換為我們希望其在以后使用的格式。 地圖是處理這項工作的要素,這對完成工作極為重要!
您將經常使用兩種映射方法。
map()是第一個,並且稍微簡單一些。 例如,假設我們想將收到的葡萄酒的分數修正為0。我們可以這樣做:

review_points_mean = reviews.points.mean()
reviews.points.map(lambda p: p - review_points_mean)

傳遞給map()的函數應該期望Series中的單個值(在上面的示例中為點值),並返回該值的轉換版本。 map()返回一個新的Series,其中所有值都已由您的函數轉換。
如果我們要通過在每一行上調用自定義方法來轉換整個DataFrame,則apply()是等效的方法。

如:

def remean_points(row):
    row.points = row.points - review_points_mean
    return row

reviews.apply(remean_points, axis='columns')

如果我們使用axis ='index'調用了reviews.apply(),則需要傳遞一個函數來轉換每一列,而不是傳遞函數來轉換每一行。
請注意,map()和apply()分別返回新的,轉換后的Series和DataFrames。 他們不會修改被調用的原始數據。 如果我們查看評論的第一行,我們可以看到它仍然具有其原始積分值。

練習

1.

What is the median of the points column in the reviews DataFrame?

median_points = reviews["points"].median()

# Check your answer
q1.check()

2.

What countries are represented in the dataset? (Your answer should not include any duplicates.)

countries = reviews["country"].unique()

# Check your answer
q2.check()

3.

How often does each country appear in the dataset? Create a Series reviews_per_country mapping countries to the count of reviews of wines from that country.

reviews_per_country = reviews["country"].value_counts ()
print(reviews_per_country)
# Check your answer
q3.check()

4.

Create variable centered_price containing a version of the price column with the mean price subtracted.

(Note: this 'centering' transformation is a common preprocessing step before applying various machine learning algorithms.)

mid=reviews["price"].mean()
centered_price = reviews["price"].map(lambda x: x-mid)

# Check your answer
q4.check()

5.

I'm an economical wine buyer. Which wine is the "best bargain"? Create a variable bargain_wine with the title of the wine with the highest points-to-price ratio in the dataset.

bargain_idx = (reviews.points / reviews.price).idxmax()
bargain_wine = reviews.loc[bargain_idx, 'title']
# Check your answer
q5.check()

6.

There are only so many words you can use when describing a bottle of wine. Is a wine more likely to be "tropical" or "fruity"? Create a Series descriptor_counts counting how many times each of these two words appears in the description column in the dataset.

n_trop = reviews.description.map(lambda desc: "tropical" in desc).sum()
n_fruity = reviews.description.map(lambda desc: "fruity" in desc).sum()
descriptor_counts = pd.Series([n_trop, n_fruity], index=['tropical', 'fruity'])
print(descriptor_counts)
# Check your answer
q6.check()

7.

We'd like to host these wine reviews on our website, but a rating system ranging from 80 to 100 points is too hard to understand - we'd like to translate them into simple star ratings. A score of 95 or higher counts as 3 stars, a score of at least 85 but less than 95 is 2 stars. Any other score is 1 star.

Also, the Canadian Vintners Association bought a lot of ads on the site, so any wines from Canada should automatically get 3 stars, regardless of points.

Create a series star_ratings with the number of stars corresponding to each review in the dataset.

def help(row):
    if(row["country"]=="Canada"):
        return 3
    if(row["points"]>=95):
        return 3
    elif(row["points"]>=85):
        return 2
    else:
        return 1
   
   
   
        
star_ratings =  reviews.apply(help,axis='columns')

print(star_ratings)


# Check your answer
q7.check()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM