how to evenly distribute values in array python

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-28 08:26:56

问题


Suppose I have df with 16 index and I want to evenly distribute number A-L

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

My desired output is:

1       A
2       A
3       B
4       B
5       C
6       C
7       D
8       D
9       E
10      F
11      G
12      H
13      I
14      J
15      K
16      L

Is there any possible way to do this

rname is second column , df2 is first column , my way was np.repeat(rname, np.ceil(len(df2) / len(rname)))[:len(df2)]


回答1:


You can do:

df['new_col'] = np.sort((np.arange(16) % 12) +1)



回答2:


This may help you

import numpy as np
rname = ['A','B','C','D','E','F','G','H','I','J','K','L']

n_times = int(np.ceil(len(data) / len(rname)))

lst = np.repeat(rname,n_times)

n_elems = (len(df) - len(rname))

output = list(lst[:n_elems*n_times]) + list(rname[n_elems:])
print(output)

OUtput

['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']



回答3:


df = pd.read_clipboard(header=None)
ar_int = [int(x) for x in np.arange(1, 13, (12/16))]
df[1] = ar_int


print(df)


    0   1
0   1   1
1   2   1
2   3   2
3   4   3
4   5   4
5   6   4
6   7   5
7   8   6
8   9   7
9   10  7
10  11  8
11  12  9
12  13  10
13  14  10
14  15  11
15  16  12

For your string comment, you can do this.

alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ar_int = [alphabet[int(x)] for x in np.arange(0, 12, (12/16))]
df[1] = ar_int
print(df)

    0   1
0   1   A
1   2   A
2   3   B
3   4   C
4   5   D
5   6   D
6   7   E
7   8   F
8   9   G
9   10  G
10  11  H
11  12  I
12  13  J
13  14  J
14  15  K
15  16  L


来源:https://stackoverflow.com/questions/61546753/how-to-evenly-distribute-values-in-array-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!