[英]How to get percentage of valid data per column according to an indicator in dataframe
[英]How to calculate percentage per year of a dataframe column with qualitative data?
假設我的 dataframe 如下所示:
建造年份 | 品牌 |
---|---|
2010 | 奔馳 |
2010 | 奔馳 |
2010 | 寶馬 |
2010 | 起亞 |
2011年 | 豐田 |
2011年 | 奔馳 |
2011年 | 奔馳 |
2012 | 特斯拉 |
我想找到構建年份和品牌的所有獨特組合,然后他們計算值並計算每年每種顏色的百分比。 目前我有這個:
df.groupby(["Build year", "Brand"]).count()
有沒有一種簡單的方法可以將其轉換為每年的百分比? 所需的 output 是:
建造年份 | 品牌 | 數數 | 年度計數的百分比 |
---|---|---|---|
2010 | 奔馳 | 2個 | 0.5 |
2010 | 寶馬 | 1個 | 0.25 |
2010 | 起亞 | 1個 | 0.25 |
2011年 | 豐田 | 1個 | 0.33 |
2011年 | 奔馳 | 2個 | 0.66 |
2012 | 特斯拉 | 1個 | 1個 |
您可以使用 lambda function 計算年度計數的百分比,如下所示:
grouped_df = df.groupby(["Build year", "Brand"])
counts = grouped_df.size().reset_index(name='Count')
counts['Percentage of annual count'] = grouped_df.apply(lambda x: 100 * x.count() / x.count().sum())
完整代碼示例
import pandas as pd
data = {'Build year': [2010, 2010, 2010, 2010, 2011, 2011, 2011, 2012],
'Brand': ['Mercedes', 'Mercedes', 'BMW', 'Kia', 'Toyota', 'Mercedes', 'Mercedes', 'Tesla']}
df = pd.DataFrame(data)
grouped_df = df.groupby(["Build year", "Brand"])
counts = grouped_df.size().reset_index(name='Count')
counts['Percentage of annual count'] = grouped_df.apply(lambda x: 100 * x.count() / x.count().sum())
print(counts)
Output
Build year Brand Count Percentage of annual count
0 2010 Mercedes 2 50.00
1 2010 BMW 1 25.00
2 2010 Kia 1 25.00
3 2011 Toyota 1 33.33
4 2011 Mercedes 2 66.67
5 2012 Tesla 1 100.00
希望能幫助到你
無需按構建年份和品牌分組,您只需按構建年份分組,並使用.value_counts
:
import pandas as pd
df = pd.read_clipboard() # Your df here
groups = df.groupby("Build year")
count = groups.value_counts()
percentage = groups.value_counts(normalize=True)
out = pd.concat([count, percentage], axis=1, keys=["Count", "Percentage of annual count"])
Count Percentage of annual count
Build year Brand
2010 Mercedes 2 0.500000
BMW 1 0.250000
Kia 1 0.250000
2011 Mercedes 2 0.666667
Toyota 1 0.333333
2012 Tesla 1 1.000000
方法鏈接方法(假設名稱沒有空格)可能如下所示:
(
df.groupby(["build_year","brand"])
.agg(count=('build_year', "count"))
.assign(Percentage_of_annual_count =
lambda x: x["count"]/x.groupby("build_year")["count"]
.transform(lambda x: sum(x)))
)
完整解決方案:
df = pd.DataFrame({
"build_year":[2010,2010,2010,2010,2011,2011,2011,2012,],
"brand":["Mercedes","Mercedes","BMW","Kia","Toyota","Mercedes","Mercedes","Tesla",]
})
(
df.groupby(["build_year","brand"])
.agg(count=('build_year', "count"))
.assign(Percentage_of_annual_count =
lambda x: x["count"]/x.groupby("build_year")["count"]
.transform(lambda x: sum(x)))
)
Output:
count Percentage_of_annual_count
build_year brand
2010 BMW 1 0.250000
Kia 1 0.250000
Mercedes 2 0.500000
2011 Mercedes 2 0.666667
Toyota 1 0.333333
2012 Tesla 1 1.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.