0

I can't find solution to my problem. I have dataframe like

import pandas as pd
df = pd.DataFrame({'A':[4,5,4,5,5,4],
                   'B':[7,8,9,4,2,3],
                   'C':[1,3,5,7,1,0]})

I'd like to make 5 new columns B_1, B_2, ..., B_5 in which i would like define cells based on function x-i, where x is cell value and i is iteration step (1,..,5) - it would be enough to have desired result for column B. B_1 should be [6,7,8,3,1,2] etc.. Can you please give me some hints?

Thanks

3
  • So df['B_1'] = df['B'] - 1? Commented Apr 19, 2020 at 18:46
  • yeah, but would be glad to see solution using loop. I need it for larger and more complicated data sets. Commented Apr 19, 2020 at 18:53
  • it would be helpful if u provide ur expected output, just as u posted an input dataframe. Commented Apr 19, 2020 at 22:25

1 Answer 1

1

In the case of having five iterations, and them being known in advance:

for col in df.columns:
    for i in range(1, 6):
        df[f'{col}_{i}'] = df[col] - i
Sign up to request clarification or add additional context in comments.

7 Comments

thanks, works really good, but something is wrong when my column name have more than one letter in name; do you know what's happening? for example for name 'Age' instead of 'A'
Shouldn't matter. df.columns is a list of strings, whether it contains 'A' or 'Age' is indifferent to the rest of the code.
I changed column name 'A' for 'Age' and tried to do the same thing just for this column, but this time some error is happening ` for col in df.columns[0]: for i in range(1, 6): df[f'{col}_{i}'] = df[col] - i`
Why did you add [0]?
The it's going to loop through the string letter by letter. If you only want it for a certain column just col = 'A' and get rid of the first for loop.
|

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.