0
3

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.

pandasでグループごとに行単位で比率を算出

Posted at

環境

  • Python 3.8
  • pandas 1.0.1

内容

pandasで、グループごとに行単位で比率を出したいです。
特に難しくはないのですが、コードの書き方に悩んでしまったので備忘録としてQiitaに記事を残します。

import pandas

df = pandas.DataFrame({
    "name": ["Alice", "Bob","Carol", "Dave","Eve"],
    "class": ["A", "A","A", "B", "B"],
    "sex": ["F", "M","F", "M","F"],
    "worktime": [1, 2,3, 4,5],
})
print(df)

#     name class sex  worktime
# 0  Alice     A   F         1
# 1    Bob     A   M         2
# 2  Carol     A   F         3
# 3   Dave     B   M         4
# 4    Eve     B   F         5



# "sex"ごとにworktimeの比率を算出
df["ratio_per_sex"] = df.groupby(["sex"])["worktime"].apply(lambda e: e / e.sum())
print(df.sort_values("sex"))

#     name class sex  worktime  ratio_per_sex
# 0  Alice     A   F         1       0.111111
# 2  Carol     A   F         3       0.333333
# 4    Eve     B   F         5       0.555556
# 1    Bob     A   M         2       0.333333
# 3   Dave     B   M         4       0.666667


参考サイト

https://stackoverflow.com/questions/23377108/pandas-percentage-of-total-with-groupby
https://teratail.com/questions/229246

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?