2

suppose I have the following dataframe:

import pandas as pd
df = pd.DataFrame({'return':[10, 28, 32, 50, 25]})

I want to set 25 (last element) to be 100 in a new column and then work backwards doing 50*100/25=200, 32*100/25=32*200/50=128..and so on

   return index
0      25  
1      28   
2      32   128
3      50   200
4      25   100

Is there any way of doing this in -preferably- one line. Thanks!

df['index']=.... ???
1
  • 4
    df['index'] = df['return'] * 4? Commented Jan 11, 2019 at 15:45

3 Answers 3

2

You can use iat to extract the last value of a series:

df['index'] = df['return'] * 100 / df['return'].iat[-1]

print(df)

   return  index
0      10   40.0
1      28  112.0
2      32  128.0
3      50  200.0
4      25  100.0
Sign up to request clarification or add additional context in comments.

Comments

1

Yeah it's possible with One line. Just use df['return'].iloc[-1] to get the last value of the return column and then simple do like below-

import pandas as pd
df = pd.DataFrame({'return':[10, 28, 32, 50, 25]})
df['index'] = (df['return'] * 100  / df['return'].iloc[-1]).astype(int)
print(df)

Output:

       return  index
0      10     40
1      28    112
2      32    128
3      50    200
4      25    100

2 Comments

In the general case you likely don't want to convert to int. Just here we have an int factor because 25 is a divisor of 100.
@jpp agreed sir, I just follow the OP's expected output that's why converted to int
0

Maybe like this?

import pandas as pd
df = pd.DataFrame({'return':[10, 28, 32, 50, 25]})

last = df["return"].iloc[-1] 
df['index'] = df['return'].apply(lambda x: x*(100/last))

df

It gives:

    return  index
0   10  40.0
1   28  112.0
2   32  128.0
3   50  200.0
4   25  100.0

4 Comments

This would be good if instead of hardcoding 25 you would do last = df["return"].iloc[-1] and then df['index'] = df['return'].apply(lambda x: x*(100/last))
Question: using lambda functions is the same as vectorizing the code? Or does it take as much time as a for loop through all the values?
@Oniropolo No, it's the opposite.
If possible don't use apply() with lambda functions. It's slower than vectorized operations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.