【问题标题】:how do i loop over values within a for loop in python?我如何在python的for循环中循环值?
【发布时间】:2022-11-11 21:01:13
【问题描述】:

我有一个df

    1   1   2   2
    2   2   1   1

我写了一个函数:
拿df
在 for 循环中,添加具有默认值的行
用随机选择的列中的另一个值替换值
写入 csv

这是我的代码。

def add_x(df, max):
    gt_w_x = df.copy()
    counter = 0


    for i in range(1, max):
        if len(gt_w_x) != max:
            counter+=1
            # add new row with default value
            gt_w_x.loc[-1,:] = 1
        
            # reset index
            gt_w_x = gt_w_x.reset_index(drop=True)
        
            # how to loop over these values for x ??
            x = 1
            #x = 2
        
            # assign value 'X' to x randomly selected cols on last row 
            gt_w_x.iloc[-1:, random.sample(list(range(gt_w_x.shape[1])), x)] = 'X'
        
            x = str(x)
            n = str(counter)
        
            # write to file
            df_path = 'test/' + x + '_' + n + '.csv'
            gt_w_x.to_csv(df_path) 

max = 4
add_x(df, max)

我系统上的输出是
测试/1_1.csv
测试/1_2.csv

猫测试/1_1.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0

猫测试/1_2.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0
3,1.0,X,1.0,1.0

如何循环 x 的值? x = 1 和 x = 2 的期望输出是
测试/1_1.csv
测试/1_2.csv
测试/2_1.csv
测试/2_2.csv

目前,我通过注释掉 x 的不同值来运行该函数,这是次优的。

【问题讨论】:

  • 对不同的x 值使用另一个for 循环。

标签: python pandas


【解决方案1】:

您可以使用嵌套的 for 循环。它的工作方式与您在函数开头所拥有的一样:

...
    for i in range(1, max):
        if len(gt_w_x) != max:
            ...

            for x in range(1,3):

                # assign value 'X' to x randomly selected cols on last row 
                gt_w_x.iloc[-1:, random.sample(list(range(gt_w_x.shape[1])), x)] = 'X'
    
                x = str(x)
                n = str(counter)
    
                # write to file
                df_path = 'test/' + x + '_' + n + '.csv'
                gt_w_x.to_csv(df_path)


【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2021-10-28
    • 1970-01-01
    • 2023-03-14
    • 2022-10-20
    相关资源
    最近更新 更多