简体   繁体   English

Python - 循环列名

[英]Python - loop column names

I can't find solution to my problem.我找不到我的问题的解决方案。 I have dataframe like我有 dataframe 之类的

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?我想创建 5 个新列 B_1、B_2、...、B_5,我想在其中定义基于 function xi 的单元格,其中 x 是单元格值,i 是迭代步骤 (1,..,5) - 它足以获得 B 列所需的结果。B_1 应该是 [6,7,8,3,1,2] 等。你能给我一些提示吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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