LoginSignup
0
0

More than 3 years have passed since last update.

pandas DataFrame からpython標準のプリミティブ型で値を取得する

Posted at

■課題 DataFrameの値取得はpython標準のプリミティブ型の値が返らない

DataFrame から、指定した列のvalue を取る時にアクセサ[]やgetメソッドを使うと、プリミティブの値ではない、ライブラリのオブジェクトが返りました。

extractDataFrame.py
from pandas import DataFrame
def getColumnValueIn(dataFrame:DataFrame, columnKey):
    return dataFrame[columnKey]

df = DataFrame([
    ['A','Bb','cccc']
])
print(getColumnValueIn(df, 1))
print(getColumnValueIn(df, 1) == 'Bb')
出力結果.txt
0    Bb
Name: 1, dtype: object
0    True
Name: 1, dtype: bool

取得できた値は想定通りですが、pandasのライブラリのオブジェクトとして値が取得されました。
この後の処理で、条件分岐などで、値を使用する際には、少し使いづらくなってしまうため、DataFrame内の値からpython標準のプリミティブ型のデータで取得する方法を調べました。

■対応 DataFrame から一度 list に戻してからアクセスする。

DataFrame からpython 標準のlistに変換し、鍵括弧[]でアクセスできるようにします。

extractDataFrame.py
from pandas import DataFrame
def getColumnValueIn(dataFrame:DataFrame, columnKey):
    return (dataFrame.values.tolist())[0][columnKey]

df = DataFrame([
    ['A','Bb','cccc']
])
print(getColumnValueIn(df, 1))
print(getColumnValueIn(df, 1) == 'Bb')

一度ndarray に変換し、tolist()を呼ぶことで、python標準のlist オブジェクトに変換され、通常のアクセサで値がそのまま取得できました。

出力結果.txt
Bb
True

以上です。

0
0
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
0