从列表中分配重复值列 [英] Assign column of repeating values from a list
问题描述
假设我有一个数据列表.对于eg [1,2,3,4,5]
,我的DataFrame中有1704
行.现在,我只想添加具有此值的新列,但应重复到最后一行,如下所示:
Suppose I have a list of data. For eg [1,2,3,4,5]
and I have 1704
rows in my DataFrame. Now I want to add new column with this values only but it should be repeated till the last row as shown below:
1
2
3
4
5
1
2
3
4
5
..
,依此类推,直到最后一条记录.我尝试了df['New Column']=pd.Series([1,2,3,4,5])
,但是它只在前5行中插入记录,但是我希望将此系列重复到最后.我提到了许多关于SO的帖子,但没有找到任何相关的帖子.我是熊猫框架的新手.请帮我解决一下这个.预先感谢.
and so on till the last record. I tried df['New Column']=pd.Series([1,2,3,4,5])
but it inserts record only in first 5 rows but I want this series to be repeated till the last. I referred many posts on SO but didn't found any relevant post. I am a newbie to pandas framework. Please help me with this. Thanks in advance.
推荐答案
下面,我提出两个解决方案,它们也可以处理df
的长度不是列表长度的完美倍数的情况.
Below, I propose two solutions that also handle situations where the length of df
is not a perfect multiple of the list length.
v = pd.Series([1, 2, 3, 4, 5])
df['NewCol'] = np.tile(v, len(df) // len(v) + 1)[:len(df)]
cycle
和islice
具有itertools
的纯Python方法.
cycle
and islice
A pure-python approach featuring itertools
.
from itertools import cycle, islice
it = cycle([1, 2, 3, 4, 5])
df['NewCol'] = list(islice(it, len(df)))
这篇关于从列表中分配重复值列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!