I want to create a column in a pandas dataframe such that it contains values from 10 to 100 with an increment of 10. The value of 10 is assigned to the first 10 percent of the rows and the value of 20 is assigned to the next 10% of the rows and so on. Assuming that the dataframe has a length of 153, this is what I tried:
arr = range(10, 110, 10)
np.resize(arr, 153)
I get this: array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30])
How can I fix this? I want the foll. result:
array([ 10, 10, 10, 10, 10, 10,... 100, 100, 100, 100])
Use math, generate a range of N
numbers, compute the floor division by 10% of N
and scale:
N = 153
a = (np.arange(N)//(N*0.1)+1)*10
# df = pd.DataFrame,({'col': a.astype(int)})
Or with. linspace
:
N = 153
step = 10
a = (np.linspace(10, 100+step, N+1)//step*step)[:-1]
Output (as array):
Note that the two approaches don't round numbers the same way and can give a slightly different output if N
is not a multiple of 10.
array([ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 40, 40, 40, 40, 40, 40,
40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
70, 70, 70, 70, 80, 80, 80, 80, 80, 80, 80, 80, 80,
80, 80, 80, 80, 80, 80, 90, 90, 90, 90, 90, 90, 90,
90, 90, 90, 90, 90, 90, 90, 90, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments