PandasのDataFrameの値を利用した計算結果の格納

Kaoru Mori
Sep 4, 2018 · 2 min read

Pandasでデータを計算していると、DataFrameの値を計算した結果をDataFrame上に格納しておきたいことがあります。

以下のエントリーが参考になりました。

身長と体重からBMIを計算してDataFrameに格納するコードは以下のようになりました。

import pandas as pddef calc_bmi(row):
weight = row['weight']
height = row['height']
return weight / (height * height)
df = pd.DataFrame([{'height': 1.6, 'weight': 58},
{'height': 1.5, 'weight': 55}])
df['bmi'] = df.apply(calc_bmi, axis=1)df

BMIのように条件分岐等の無い計算であれば、以下のように簡単に記述することも可能です。

df['bmi'] = df['weight'] / (df['height'] * df['height'])
Kaoru Mori

Written by

ねこぱんち研究所 主任研究員, kaoru.mori@gmail.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade