Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy and Pandas Repeat Values by Bin

I have a Dataframe or Numpy array with ascending group numbers, and I would like to assign a list of values (with equal length to the unique number of groups) repeated per group.

ID - Group
0  -  0
1  -  0
2  -  1
3  -  1
4  -  1
5  -  2
6  -  2
7  -  3

Values to assign:

[4, 2, 7, 8] # 4 maps to group 0, 2 maps to group 1 etc

Output:

ID - Group  - Val
0  -  0     -  4
1  -  0     -  4
2  -  1     -  2
3  -  1     -  2
4  -  1     -  2
5  -  2     -  7
6  -  2     -  7
7  -  3     -  8

Appreciate any suggestions, preferably without looping if there are elegant ways/native functions to solve that (looking for both Numpy and Pandas solution).

like image 975
Franc Weser Avatar asked Apr 07 '26 18:04

Franc Weser


1 Answers

Setup:

a = np.array([4, 2, 7, 8])
v = df.Group.values
dct = {}

Option 1
Using numpy indexing. (This solution assumes your groups range from 0-N:

dct['numpy_indexing'] = a[v]

Option 2
Using np.repeat. (This solution assumes your groups are not interlaced):

dct['numpy_repeat'] = np.repeat(a, np.bincount(v))

Option 3
Using map. This approach will be slower than the others, but is a bit more flexible, as it allows for interlaced groups and non-linear groups:

d = dict(zip(np.unique(v), a))

dct['pandas_map'] = df.Group.map(d)

Output

df.assign(**dct)

   ID  Group  numpy_indexing  numpy_repeat  pandas_map
0   0      0               4             4           4
1   1      0               4             4           4
2   2      1               2             2           2
3   3      1               2             2           2
4   4      1               2             2           2
5   5      2               7             7           7
6   6      2               7             7           7
7   7      3               8             8           8
like image 128
user3483203 Avatar answered Apr 10 '26 07:04

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!