从列表中分配重复值的列

Assign column of repeating values from a list

假设我有一个数据列表。对于 eg [1,2,3,4,5],我的 DataFrame 中有 1704 行。现在我只想添加具有此值的新列,但应该重复到最后一行,如下所示:

1  
2  
3  
4  
5  
1  
2  
3  
4  
5  
..  

以此类推,直到最后一条记录。我试过 df['New Column']=pd.Series([1,2,3,4,5]) 但它只在前 5 行插入记录,但我希望这个系列重复到最后。我在 SO 上提到了很多 post,但没有找到任何相关的 post。我是 pandas 框架的新手。请帮我解决一下这个。提前致谢。

下面,我提出了两个解决方案,它们也可以处理 df 的长度不是列表长度的完美倍数的情况。

np.tile

v = pd.Series([1, 2, 3, 4, 5])
df['NewCol'] = np.tile(v, len(df) // len(v) + 1)[:len(df)]  

cycleislice

itertools.

为特色的纯 python 方法
from itertools import cycle, islice

it = cycle([1, 2, 3, 4, 5])
df['NewCol'] = list(islice(it, len(df)))

或者你可以在基本计算中进行。

df['New']=(df.index%5).values
df.New=df.New.add(1)