Ad

Element-wise Division With Accumulated Numbers In Python?

- 1 answer

The title may come across as confusing (honestly, not quite sure how to summarize it in a sentence), so here is a much better explanation:

I'm currently handling a dataFrame A regarding different attributes, and I used a .groupby[].count() function on a data column age to create a list of occurrences:

A_sub = A.groupby(['age'])['age'].count()

A_sub returns a Series similar to the following (the values are randomly modified):

age
1    316
2    249
3    221
4    219
5    262
...
59    1
61    2
65    1
70    1
80    1
Name: age, dtype: int64

I would like to plot a list of values from element-wise division. The division I would like to perform is an element value divided by the sum of all the elements that has the index greater than or equal to that element. In other words, for example, for age of 3, it should return

221/(221+219+262+...+1+2+1+1+1)

The same calculation should apply to all the elements. Ideally, the outcome should be in the similar type/format so that it can be plotted.

Ad

Answer

Here is a quick example using numpy. A similar approach can be used with pandas. The for loop can most likely be replaced by something smarter and more efficient to compute the coefficients.

import numpy as np

ages = np.asarray([316, 249, 221, 219, 262])
coefficients = np.zeros(ages.shape)

for k, a in enumerate(ages):
    coefficients[k] = sum(ages[k:])

output = ages / coefficients

Output:

array([0.24940805, 0.26182965, 0.31481481, 0.45530146, 1.        ])

EDIT: The coefficients initizaliation at 0 and the for loop can be replaced with:

coefficients = np.flip(np.cumsum(np.flip(ages)))
Ad
source: stackoverflow.com
Ad