pandas:データ取り出し【ループ処理】記述例


前提

サンプルコード

NumPy配列で取り出す

データ作成

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(9).reshape(3,3), columns=['p','q','r'])
print(df)
print(df.shape)
   p  q  r
0  0  1  2
1  3  4  5
2  6  7  8
(3, 3)
  • サイズ(3,3)のデータ(データフレーム)を作成

例1

for line in df[['p','q']].values:
    a = line[0]
    b = line[1]
    print(f'{a},{b}')
0,1
3,4
6,7
  • df[['p’,’q’]]
    • p列,q列を取り出し
  • df.values
    • ndarrry(NumPy)に変換する
    • p列の取り出しline[0]
    • q列の取り出しline[1]

例2

for a,b in zip(df.p.values,df.q.values):
    print(f'{a},{b}')
0,1
3,4
6,7
  • for文で変数代入ができる

pandasデータで取り出す

例1

for i in range(len(df)):
    row = df.iloc[i]
    print(row)
    print(type(row))
p    0
q    1
r    2
Name: 0, dtype: int64
<class 'pandas.core.series.Series'>
p    3
q    4
r    5
Name: 1, dtype: int64
<class 'pandas.core.series.Series'>
p    6
q    7
r    8
Name: 2, dtype: int64
<class 'pandas.core.series.Series'>
  • range(len(df))
  • df.iloc[…]
    • インデックス番号を引数にしてデータを取り出す
    • df.locも使える
    • 取り出したデータはSeriesになる

例2

for data in df.iloc:
    print(data)
    print(type(data))
p    0
q    1
r    2
Name: 0, dtype: int64
<class 'pandas.core.series.Series'>
p    3
q    4
r    5
Name: 1, dtype: int64
<class 'pandas.core.series.Series'>
p    6
q    7
r    8
Name: 2, dtype: int64
<class 'pandas.core.series.Series'>
  • 例1と比較して
    • for文で変数に設定できる
    • df.locは使えない
  • df.iloc
    • 1行ごとに取り出せる
    • 取り出したデータはSeriesになる

インデックス番号も併せて取得(Seriesの場合)

データ作成

import pandas as pd
s = pd.Series(['A', 'B', 'C'])
print(s)
print(type(s))
0    A
1    B
2    C
dtype: object
<class 'pandas.core.series.Series'>
  • 3つのデータを持つSeriesを作成

ループ処理

for index, value in s.items(): #indexと値を返す
    print(f"Index : {index}, Value : {value}")
Index : 0, Value : A
Index : 1, Value : B
Index : 2, Value : C
  • s.items()で取り出す
  • index
    • データのインデックス番号
  • value
    • インデックス番号に対応する値

インデックス番号も併せて取得(DataFrameの場合)

データ作成

import pandas as pd
df = pd.DataFrame({'id':['01','02','03'],'key':['x','y','z'],'value':[10,20,30]})
print(df)
print(df.shape)
   id key  value
0  01   x     10
1  02   y     20
2  03   z     30
(3, 3)
  • サイズ(3,3)のデータ(データフレーム)を作成

例1

for index, item in df.iterrows():
    print(index)
    print(item)
    print(type(item))
0
id       01
key       x
value    10
Name: 0, dtype: object
<class 'pandas.core.series.Series'>
1
id       02
key       y
value    20
Name: 1, dtype: object
<class 'pandas.core.series.Series'>
2
id       03
key       z
value    30
Name: 2, dtype: object
<class 'pandas.core.series.Series'>
  • df.itterrows()で取り出せる
  • index
    • データのインデックス番号
  • item
    • インデックス番号に対するデータ
    • 1レコードなのでSeriesになる

例2

for i, data in enumerate(df.values):
    print(f'no:{i},data:{data}')
no:0,data:['01' 'x' 10]
no:1,data:['02' 'y' 20]
no:2,data:['03' 'z' 30]
  • enumerate(…)で行番号を付加する
  • df.valuesでndarray(NumPy配列)で取得する


Posted by futa