13
19

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 5 years have passed since last update.

複数列の値を引数に計算→新しい列に結果代入

Last updated at Posted at 2018-07-29

忘備録です。

  • エクセルっぽく、列の値を使って掛け算などの計算をして新たな列に代入する。

流れは、まず空の列をつくり、
引数に列を取るような関数を作って、axis=1方向にデータフレームにapply。

import pandas as pd
import numpy as np

#サンプルデータ作成
data = {"name":["高橋","鈴木","田中","松本"],
        "score": [80, 90, 70, 75],
        "number":[1,2,1,3],
        "sex":["m", "f", "f", "m"]}

df = pd.DataFrame(data,columns=["name","sex","number","score"])
print(df)

  name sex  number  score
0   高橋   m       1     80
1   鈴木   f       2     90
2   田中   f       1     70
3   松本   m       3     75

結果を入れる空の列を作成。

df["result"]=np.nan
print(df)
  name sex  number  score  result
0   高橋   m       1     80     NaN
1   鈴木   f       2     90     NaN
2   田中   f       1     70     NaN
3   松本   m       3     75     NaN

numberとscoreを掛け算する関数をつくる。

#今回は番号で列指定。
def kakezan(x):
    return x.iloc[2] * x.iloc[3]

applyする。


df["result"] = df.apply(kakezan, axis=1)
print(df)
  name sex  number  score  result
0   高橋   m       1     80      80
1   鈴木   f       2     90     180
2   田中   f       1     70      70
3   松本   m       3     75     225

※ご指摘等あればよろしくお願いします。

13
19
1

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
13
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?