Assign column of repeating values from a list

别来无恙 提交于 2020-01-03 02:25:11

问题


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  
..  

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.


回答1:


Below, I propose two solutions that also handle situations where the length of df is not a perfect multiple of the list length.

np.tile

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

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)))



回答2:


Or you can just do within basic calculation.

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


来源:https://stackoverflow.com/questions/47185315/assign-column-of-repeating-values-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!