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 1 year has passed since last update.

kuvoAdvent Calendar 2022

Day 21

【学習ノート】Pandas 〜基本操作②〜

Posted at

はじめに

データ分析が必要となり、学習を進める上でいつでも見返せるように毎日の学習をメモします。

Dataframe

※ データ分析を極めたいため、seriesの記載は省略する。

index、columnを指定してDataframeを生成する

df = pd.DataFrame([[1, 10], [2, 20], [3, 30], [4, 40]], index=['a', 'b', 'c', 'd'], columns=['col1', 'col2'])
print(df)

#    col1  col2
# a     1    10
# b     2    20
# c     3    30
# d     4    40

辞書から生成する

data = {'col1' : [1, 2, 3], 'col2' : [10, 20, 30]}
df = pd.DataFrame(data)
print(df)

#    col1  col2
# 0     1    10
# 1     2    20
# 2     3    30

統計量計算

df.count()	#要素数
df.mean()	#平均
df.max()    #最大値
df.min()    #最小値
df.var()    #分散

↑ describeを使うことで基本的な統計量を一括で取得することが可能

df.describe()
#        col1  col2
# count   3.0   3.0
# mean    2.0  20.0
# std     1.0  10.0
# min     1.0  10.0
# 25%     1.5  15.0
# 50%     2.0  20.0
# 75%     2.5  25.0
# max     3.0  30.0

取得

# col1を取得する
print(df['col1'])
# または print(df.col1)

# a    1
# b    2
# c    3
# Name: col1, dtype: int64

loc・iloc

locはラベル名、つまりindexを指定し、ilocはinteger-location、つまり位置を表す整数でアクセスする。

print(df.loc[0]) 
# col1     1
# col2    10
# Name: 0, dtype: int64

print(df.loc[0]['col1'])
# 1
df.iloc[1]
# col1     2
# col2    20
# Name: 1, dtype: int64

where

import pandas as pd
df = pd.DataFrame([[1, 10], [2, 20], [3, 30], [4, 40]], columns=['col1', 'col2'])

# 添字でフィルタ条件指定
df[df['col1'] > 2]

#    col1  col2
# 2     3    30
# 3     4    40


# whereを使用

df.where(df['col1'] > 2)
#    col1  col2
# 0   NaN   NaN
# 1   NaN   NaN
# 2   3.0  30.0
# 3   4.0  40.0

df.where(df['col1'] > 2, 0)

#    col1  col2
# 0     0     0
# 1     0     0
# 2     3    30
# 3     4    40
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?