简体   繁体   中英

fill columns of dataframe with groups python

i have a pandas dataframe which has 1 row

key
1
2
3
...
93

and i am having no. of machines = 3 no. of machines = 3

i want to allocate equal no. of keys to each machine. ie

there are 9 keys and 3 machines, so, 3 keys should be associated with each machine. below is the required dataframe:

key    machine allocated    
1         1                 
2         1                 
3         1                 
..........

90        3
91        1
92        1
93        1  

can we do it using groupby ?

You can use floor division of arange :

df = pd.DataFrame({'key' : range(1, 10)})

N = 3
N1 = len(df.index) / N

df['machine allocated'] = ((np.arange(len(df.index)) // N1) + 1).astype(int)
print (df)
   key  machine allocated
0    1                  1
1    2                  1
2    3                  1
3    4                  2
4    5                  2
5    6                  2
6    7                  3
7    8                  3
8    9                  3

N = 2
N1 = len(df.index) / N

df['machine allocated'] = ((np.arange(len(df.index)) // N1) + 1).astype(int)
print (df)
   key  machine allocated
0    1                  1
1    2                  1
2    3                  1
3    4                  1
4    5                  1
5    6                  2
6    7                  2
7    8                  2
8    9                  2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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