Home > Blockchain >  Trying to use np.arange to create a counter that is half the length of my dataframe
Trying to use np.arange to create a counter that is half the length of my dataframe

Time:04-14

I'm trying to fill a column in my pandas dataframe that is numbered from 1, and is a counter that goes up by one incrementally. However, I want it to be exactly half the length of the data already contained in the dataframe (for example, if my dataframe had 10 rows, I want the counter to go up to 5.) I've been playing around with different solutions, and currently I have this solution:

# Fill the cycles column with however many rows exist / 2
jac_output['Cycles'] = (np.arange(1,len(jac_output) 1))//2

However, rather than halfing the length of the dataframe, it merely duplicates numbers, like this:

print(jac_output['Cycles'].head(8))

0    0
1    1
2    1
3    2
4    2
5    3
6    3
7    4

print(jac_output['Cycles'].head(7))

0    0
1    1
2    1
3    2
4    2
5    3
6    3

Any help would be greatly appreciated! I feel this should be an easy solution but I'm tearing my hair out over it!

CodePudding user response:

Use integer division by half of length of Dataframe by // for counter in numpy.where:

jac_output = pd.DataFrame({'a': range(9)})

lens = len(jac_output)
arr = np.arange(lens)
a = arr // (lens // 2)
jac_output['Cycles'] = np.where(a == 0, arr   1, np.nan)
print (jac_output)
   a  Cycles
0  0     1.0
1  1     2.0
2  2     3.0
3  3     4.0
4  4     NaN
5  5     NaN
6  6     NaN
7  7     NaN
8  8     NaN
  • Related