1

I have a pandas dataframe and I would like to add an empty column (named nb_trades). Then I would like to fill this new column with a 5 by 5 increment. So I should get a column with values 5 10 15 20 ...

Doing the below code assign the same value (last value of i) in the whole column and that's not what I wanted:

big_df["nb_trade"]='0'
for i in range(big_df.shape[0]):
    big_df['nb_trade']=5*(i+1)

Can someone help me?

4
  • 1
    Why not np.arange(5, 5*(big_df.shape[0]+1), 5)? Commented Sep 12, 2017 at 5:27
  • Thanks. However, doing this is not the result I wanted. I wanted to increment line by line within a single column. I used df['new'] = np.arange(5, df.shape[0] * 5 + 5, 5) instead. Commented Sep 12, 2017 at 5:44
  • Both are same, see the answer below! Commented Sep 12, 2017 at 5:46
  • I am sorry, you are absolutely right. Commented Sep 12, 2017 at 20:21

1 Answer 1

2

Use range or np.arrange:

df = pd.DataFrame({'a':[1,2,3]})
print (df)
   a
0  1
1  2
2  3

df['new'] = range(5, len(df.index) * 5 + 5, 5)
print (df)
   a  new
0  1    5
1  2   10
2  3   15

df['new'] = np.arange(5, df.shape[0] * 5 + 5, 5)
print (df)
   a  new
0  1    5
1  2   10
2  3   15

Solution of John Galt from comment:

df['new'] = np.arange(5, 5*(df.shape[0]+1), 5)
print (df)
   a  new
0  1    5
1  2   10
2  3   15
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Jezrael. Thnk you, the arange method worked. The range method did not match the number of rows originally.

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.