Matlas
Matlas

Reputation: 21

Python - loop column names

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

Upvotes: 0

Views: 251

Answers (1)

gosuto
gosuto

Reputation: 5741

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

Upvotes: 1

Related Questions