简体   繁体   中英

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 xi, 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM