我如何在 pandas 中创建一个列表或列,该列中的数字以 1 为步长增加,当它达到某个数字(比方说 5)时,它返回 1 并重复此过程?我的脚本如下所示,它不会按预期工作:i = 0lista = []for i in range(50): i += 1 if i == 5: continue lista.append(i)print(i)# what I wanted from this code is like :12345...# repeat printing 1-5 for 10 times
2 回答

BIG阳
TA贡献1859条经验 获得超6个赞
首先在 pandas 中使用循环是反模式,主要是如果存在矢量化解决方案,这里numpy.tile
:
df = pd.DataFrame({'col': np.tile(np.arange(1, 6), 10)})
print (df.head(12))
col
0 1
1 2
2 3
3 4
4 5
5 1
6 2
7 3
8 4
9 5
10 1
11 2

MMTTMM
TA贡献1869条经验 获得超4个赞
以我想到的最简单的方式:
lista = []
for i in range(50):
lista.append(i%5+1)
print(lista)
这也可以写成列表理解,这只是一行代码,而且更酷;)
lista = [ i%5+1 for i in range(50) ]
添加回答
举报
0/150
提交
取消