kaggleのcourseでの学びを共有していきます!
pandasコースでDataFrame型でのデータの扱いについて学んだのでそれについてです!
具体的には、pandasのgroupbyについてです。
DataFrame型で定義
import pandas as pd
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
print(reviews)
country description \
0 Italy Aromas include tropical fruit, broom, brimston...
1 Portugal This is ripe and fruity, a wine that is smooth...
... ... ...
129969 France A dry style of Pinot Gris, this is crisp with ...
129970 France Big, rich and off-dry, this is powered by inte... ttling from 2012,
this... Vintner's Reserve Wild Child Block 87 65.0 Oregon Willamette Valley Willamette Valley Paul Gregutt @paulgwine Sweet Cheeks 2012 Vintner's Reserve Wild Child... Pinot Noir Sweet Cheeks
たくさんのデータがあるので、これらを見やすくするために列ごとに同じ要素を持つものをグループとしてくくりたい。
そんなときに、使うのがgroupby()です。
groupby()の使い方
例えば、国別でまとめて扱いたいときは、
country = reviews.groupby('country').country.count()
print(country)
country
Argentina 3800
Armenia 2
...
Ukraine 14
Uruguay 109
Name: country, Length: 43, dtype: int64
このように扱うことができます。
sort_values()の使い方
さらに、これを整理して見やすくするには
sort_values()を用います。
sort_values()の引数を指定しない場合は昇順になっています。
country = reviews.groupby('country').country.count().sort_values()
print(country)
country
China 1
Slovakia 1
...
France 22093
US 54504
Name: country, Length: 43, dtype: int64
sort_values(ascending=False)とすることで降順になります。
country = reviews.groupby('country').country.count().sort_values(ascending=False)
print(country)
country
US 54504
France 22093
...
Slovakia 1
China 1
Name: country, Length: 43, dtype: int64
手持ちのデータがどのようなデータなのかを調べることは重要ですので是非活用してみてください。
スポンサーリンク
タイピングもままならない完全にプログラミング初心者から
アホいぶきんぐ
プログラミングってどこの国の言語なの~?
たった二ヶ月で
いぶきんぐ
え!?人工知能めっちゃ簡単にできるじゃん!
応用も簡単にできる…!!
という状態になるまで、一気に成長させてくれたオススメのプログラミングスクールをご紹介します!



テックアカデミーのPython+AIコースを受講した僕が本音のレビュー・割引あり! というプログラミング完全初心者だった僕が
Tech Academy(テックアカデミー)のPython×AIコース を二ヶ月間...