简体   繁体   中英

Pandas/Numpy - how to add reoccurring integers in a dataframe column that matches the length of the index

I have a pandas dataframe with several columns and 720 rows. I want to add a column with a reoccurring range of numbers (0 to 23) to this dataframe. First row being 0, twenty third row being 23, twentyfourth row is 0, etc.

I tried this:

for i in range(24):
    print(i)

df['hours(integers)']= np.ones(720) * (i)

However, it did not work. every new row became 23.

How can I make this reoccuring integer column?

Use modulo 24 , no loops are necessary here:

df = pd.DataFrame({'a':1}, index=range(720))

#default Range index
df['hours(integers)'] = df.index % 24
#any index with helper array
#df['hours(integers)'] = np.arange(len(df)) % 24

print (df.head(30))
    a  hours(integers)
0   1                0
1   1                1
2   1                2
3   1                3
4   1                4
5   1                5
6   1                6
7   1                7
8   1                8
9   1                9
10  1               10
11  1               11
12  1               12
13  1               13
14  1               14
15  1               15
16  1               16
17  1               17
18  1               18
19  1               19
20  1               20
21  1               21
22  1               22
23  1               23
24  1                0
25  1                1
26  1                2
27  1                3
28  1                4
29  1                5  

您可以在 numpy 中使用 tile 功能

df['hours(integers)'] = np.tile(list(range(24)), 30)

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