Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
6

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備忘録

Last updated at Posted at 2020-05-20

今回はPandasを使った際に、すぐに分からなかった事象のまとめです。
結構Pandasってどうやって操作すればいいのかな?って迷うことも多いので少しでも参考になれば幸いです。

使用するデータセット作成

  • まずは適当にデータセットを作成する。本記事はこの簡単なデータを例に書いていく

index = ['製品A', '製品B', '製品C']
columns = ['', '', '', '']
data = np.array([
    [0,10,20,30],
    [0,0,100,20],
    [50,100,20,40],
])

df = pd.DataFrame(data, index=index, columns=columns)
df.head()
製品A 0 10 20 30
製品B 0 0 100 20
製品C 50 100 20 40

ケース①各行の最大値,最小値に対応しているカラム名、そしてその値を抜き出して追加

  • つまり製品Aなら冬が一番大きく製品Cなら夏が一番大きい数字なので、新しいカラム「売れる季節」にその季節を挿入する
for index, row in df.iterrows():
    
#     df.ix[index, '売れる季節'] = row.argmax()
    df.ix[index, '売れる季節'] = row.idxmax() #どっちでもできる

#     df.ix[index, '売れない季節'] = row.argmin()
    df.ix[index, '売れない季節'] = row.idxmin() #どっちでもできる
    
    df.ix[index, 'MAX'] = row.max()
    df.ix[index, 'MIN'] = row.min()

df.head()

| |春 |夏 |秋 |冬 |売れる季節 |売れない季節 |MAX |MIN |
|---|---|---|---|---|---|---|---|---|---|
|製品A |0 |10 |20 |30 |冬 |春 |30 |0 |
|製品B |0 |0 |100 |20 |秋 |春 |100 |0 |
|製品C |50 |100 |20 |40 |夏 |秋 |100 |20 |

ケース②各行で最初に正の整数になるカラム名を抜き出して追加

  • つまり各製品が初めて売れ始めた季節を出したい。Aなら夏、Bなら秋という感じ
for index, row in df.iterrows():
# index[0]で最初に条件が成立したものを取り出す
    df.ix[index, '売れ始め季節'] = row[row > 0].index[0] 
    
df.head()
売れ始め季節
製品A 0 10 20 30
製品B 0 0 100 20
製品C 50 100 20 40

ケース③0が1つも入ってない行を抜き出したい

  • つまり年中売れている製品Cの行を抜き出したい
# not_zero_df = df.query('春 > 0 and 夏 > 0 and 秋 > 0 and 冬 > 0')
# not_zero_df = df.query('春 != 0 and 夏 != 0 and 秋 != 0 and 冬 != 0')

# ↑でもいいが変数として外だしも可能。下で「@」をつければいい
hoge1,hoge2,hoge3,hoge4 = 0,0,0,0 
not_zero_df = df.query('春 > @hoge1 and 夏 > @hoge2 and 秋 > @hoge3 and 冬 > @hoge4')
    
not_zero_df.head()
製品C 50 100 20 40
  • ちなみに夏のみに着目して0以外を抽出したい場合は同じくこう書けばいい(夏が0でない行を取り出す)
hoge = 0 
not_zero_df = df.query('夏 != @hoge')
    
not_zero_df.head()
製品A 0 10 20 30
製品C 50 100 20 30

今後も随時追記していく予定です

1
6
2

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?