[英]In a pandas pivot table, how do I define a function for a subset of data?
I'm working with a dataframe similar to this:我正在使用与此类似的 dataframe:
Name姓名 | Metric 1公制 1 | Metric 2公制 2 | Country国家 |
---|---|---|---|
John约翰 | 0.10 0.10 | 5.00 5.00 | Canada加拿大 |
Jane简 | 0.50 0.50 | Canada加拿大 | |
Jack杰克 | 2.00 2.00 | Canada加拿大 | |
Polly波莉 | 0.30 0.30 | Canada加拿大 | |
Mike麦克风 | Canada加拿大 | ||
Steve史蒂夫 | Canada加拿大 | ||
Lily百合 | 0.15 0.15 | 1.20 1.20 | Canada加拿大 |
Kate凯特 | 3.00 3.00 | Canada加拿大 | |
Edward爱德华 | 0.05 0.05 | Canada加拿大 | |
Pete皮特 | 0.02 0.02 | 0.03 0.03 | Canada加拿大 |
I am trying to define a function that will calculate the percentage of metrics that are greater than 1 of the rows that have metrics .我正在尝试定义一个 function ,它将计算大于 1的具有 metrics 的行的百分比。 I expect that for Metric 1, I should get 25%, and for Metric 2, I should get 66%.我预计对于 Metric 1,我应该得到 25%,对于 Metric 2,我应该得到 66%。 However, my function is returning results based on the total number of rows.但是,我的 function 根据总行数返回结果。 Here's my code:这是我的代码:
import pandas as pd
import io
df = pd.read_csv(io.BytesIO(data_to_load['metric data.csv']))
df = df.fillna(0)
def metricgreaterthanone(x):
return (x>1).sum()/len(x!=0)
pd.pivot_table(df,index=['Country'],values=["Name","Metric 1","Metric 2"],aggfunc={'Name':pd.Series.nunique, "Metric 1":metricgreaterthanone,"Metric 2":metricgreaterthanone})
The result I get is:我得到的结果是:
Country国家 | Metric 1公制 1 | Metric 2公制 2 | Name姓名 |
---|---|---|---|
Canada加拿大 | 0.2 0.2 | 0.2 0.2 | 10 10 |
So the function is returning the percent of all rows all that are greater than 1. Any ideas on how to fix this?所以 function 返回所有大于 1 的行的百分比。关于如何解决这个问题的任何想法?
x!=0
returns a boolean array, so len()
is not counting the number of Trues. x!=0
返回一个 boolean 数组,因此len()
不计算 True 的数量。
Try尝试
def metricgreaterthanone(x):
return (x>1).sum()/(x!=0).sum()
It seems that you have empty string ""
instead of numbers.似乎您有空字符串""
而不是数字。 You can try:你可以试试:
def metricgreaterthanone(x):
n = pd.to_numeric(x, errors="coerce")
return (n > 1).sum() / n.notna().sum()
x = pd.pivot_table(
df,
index=["Country"],
values=["Name", "Metric 1", "Metric 2"],
aggfunc={
"Name": pd.Series.nunique,
"Metric 1": metricgreaterthanone,
"Metric 2": metricgreaterthanone,
},
)
print(x)
Prints:印刷:
Metric 1 Metric 2 Name
Country
Canada 0.25 0.666667 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.