Assign column of repeating values from a list

2019-07-26 13:22发布

问题:

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)