首页 > 解决方案 > 对于每次迭代,只将数据添加到 pandas 中空数据框的几列

问题描述

我有一个代码,其中有一个循环,每次迭代的输出都创建一个df1具有不同列名的数据框,比如在迭代 1 中,df1创建的数据框给我列 A、B、C,在迭代 2 中列是 A ,X,D。每个数据帧只有一条记录作为输出。

总共可以有 26 个不同的列和一个 iteration_seq 列。df2我创建了一个包含所有可能列的 pandas 空数据框。

df2 = pd.DataFrame(columns = ['iteration_seq','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                          'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                          'U', 'V', 'W', 'X', 'Y', 'Z'])



lis = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 
   'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y', 'Z']

import random
random.shuffle(lis)
import numpy as np

for i in range(len(lis)-1):
    pax = lis[i]   # we have problem from here, say I want to take any aribitrary variable and put random value in that, and then update the df2, and later append the df2 in the df1 
    df2 = pd.DataFrame(columns = ['iteration_seq'])
    df2[pax] = np.random.rand(1,1000)) # and how to take a variable value as column value, in R we had the option of "with"
    df2['iteration_seq'] = i+1

如何将循环的每次迭代的值作为空数据帧 df2 中的单独行仅用于 df1 中循环输出中的列,以及指定迭代次数的附加列。

标签: pythonpandas

解决方案


推荐阅读