我有一只熊猫数据,有几列和720行。我想在这个dataframe中添加一个重出现的数字范围(0到23)的列。第一行是0,第二十三行是23,第二十四行是0,等等。
我试过这个:
for i in range(24):
print(i)
df['hours(integers)']= np.ones(720) * (i)但是,这是行不通的。每排新的一排都变成了23岁。
如何使这个重复出现的整数列出现?
发布于 2020-09-18 11:23:25
使用modulo 24,这里不需要循环:
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)) % 24print (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 发布于 2020-09-18 13:02:45
您可以在numpy中使用平铺函数。
df['hours(integers)'] = np.tile(list(range(24)), 30)https://stackoverflow.com/questions/63954783
复制相似问题