0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pandas での reset_index() で series を dataframe にする

Posted at

データサイエンス100本ノックやっています。
わからなかったことのメモです。

P-030: レシート明細データフレーム(df_receipt)に対し、
店舗コード(store_cd)ごとに売上金額(amount)の標本分散を計算し、降順でTOP5を表示せよ。

という問題で、自分の答えは以下でしたがうまくいきませんでした。
df_receipt.groupby("store_cd").amount.var(ddof=0).sort_values("amount", ascending=False).head(5)

正解は以下でした。
df_receipt.groupby('store_cd').amount.var(ddof=0).reset_index().sort_values('amount', ascending=False).head(5)

違いは .reset_index()だけです。
reset_index() はインデックスを振り直すためのメソッドです。
ただし、結果として series型 として取り出したデータを dataframe型 に変換することになるみたいです。
sort_values()series では使えないので reset_index()dataframe に変更する必要があった、ということのようです。

ここまでの問題も回答では reset_index() を使っていましたが、自分は使っていませんでした。
reset_index()をしなくても同じ回答が出ていたので、なんで使うのかわからなかったんですが、こういう理由だったんですね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?