简体   繁体   English

如何消除负值并计算正整数的总和?

[英]How to eliminate negative values and calculate the sum of just positive integers?

I have an excel sheet to export the data from, I need to sum two columns individually and divide them to get the answer.我有一个 excel 表可以从中导出数据,我需要将两列单独相加并将它们分开以获得答案。 but, while doing sum operation I don't want my code to consider the negative values from 'YTD chg hrs actual' column (ie, I just wanted to sum only positive values).但是,在进行求和运算时,我不希望我的代码考虑来自“YTD chg hrs actual”列的负值(即,我只想对正值求和)。 how could I achieve this from the following code?我怎么能从下面的代码中实现这一点?

util = "my file location goes here"
utilization_by_region=(((util.groupby(['BA Name','PC Name'])['YTD Chg Hrs Actual']).sum())/(util.groupby(['BA Name','PC Name'])['YTD Normal Hrs Actual'].sum())).replace(np.inf,np.nan)
utilization_by_service_line=((util.groupby(['PC Name','BA Name'])['YTD Chg Hrs Actual'].sum())/(util.groupby(['PC Name','BA Name'])['YTD Normal Hrs Actual'].sum())).replace(np.inf,np.nan)
print(utilization_by_region.fillna(0),utilization_by_service_line.fillna(0))

Imagine you have a dataframe named df , and it has a column of integer numbers.假设您有一个名为df的数据df ,它有一列整数。 This code will help you to compute the summation of only positive values.此代码将帮助您计算仅正值的总和。

# df is your dataframe, 'A' is the column.
sum = df[df['A']>0].sum()

you can find positive numbers indexes and only compute the summation of the resulted subframe.您可以找到正数索引并仅计算结果子帧的总和。

For example purpose let's create the following DataFrame:例如,让我们创建以下 DataFrame:

df = pd.DataFrame({'A': [ 2.5, 3.5, -10.1 -7.5, 3.0 ],
    'B': [ 3.5, -10.2 -7.8, 0.5, -0.1 ]})

Then, to leave only positive values, create an auxiliary DataFrame:然后,为了只留下正值,创建一个辅助 DataFrame:

df2 = df.where(df > 0, 0)

Then, to compute sum(A) / sum(B), execute:然后,要计算 sum(A) / sum(B),请执行:

df2.A.sum() / df2.B.sum()

For the above example data, the result is 2.25 .对于上面的示例数据,结果是2.25

Now change column names to your columns and you have your result.现在将列名称更改为您的列,您就可以得到结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM