Rom*_*Die 1 python list repeat pandas
假设我有一个数据列表.对于eg [1,2,3,4,5]和我有1704我的数据帧行.现在我想添加只有这个值的新列,但应该重复到最后一行,如下所示:
1
2
3
4
5
1
2
3
4
5
..
Run Code Online (Sandbox Code Playgroud)
等到最后一个记录.我试过df['New Column']=pd.Series([1,2,3,4,5])但它只在前5行中插入记录,但我希望这个系列重复到最后一行.我在SO上提到了很多帖子,但没有找到任何相关的帖子.我是pandas框架的新手.请帮我解决一下这个.提前致谢.
下面,我提出了两种解决方案,它们也处理长度df不是列表长度的完美倍数的情况.
np.tilev = pd.Series([1, 2, 3, 4, 5])
df['NewCol'] = np.tile(v, len(df) // len(v) + 1)[:len(df)]
Run Code Online (Sandbox Code Playgroud)
cycle 和 islice一种纯粹的蟒蛇方法itertools.
from itertools import cycle, islice
it = cycle([1, 2, 3, 4, 5])
df['NewCol'] = list(islice(it, len(df)))
Run Code Online (Sandbox Code Playgroud)