3

I have some quarter level data for finance deals, so a pretty big dataset. I now want to add the following values to a new column repeated over and over:

[-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12]

The column should then look something like this:

A
-12
-11
-10
...
11
12
-12
-11
...
11
12

So basically just that list repeating over and over until the last row of my Dataframe. I hope this question is clear enough.

3 Answers 3

3

Try this:

N = len(df)
df['A'] = pd.Series(np.tile(lst, N//len(lst))).iloc[:N]
Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't seem to be working, the values aren't repeating as I want them to. They are all jumbled up and seem to follow no particular pattern. I also get this message: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: pandas.pydata.org/pandas-docs/stable/…
Nevermind, your solution worked. I forgot to reindex my dataframe thats is why the numbers werent repeating as I wanted them to. Thanks for your answer
2

itertools.cycle will repeat an iterator indefinitely, and itertools.islice takes only the leading portion.

pd.Series(list(itertools.islice(itertools.cycle(range(-12,13)), len(df))))

Comments

2

Using numpy place

a=np.zeros(len(data_file))
np.place(a,a>=0,np.array([1,2]))
a
Out[526]: array([1., 2., 1., 2.])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.