简体   繁体   English

用循环填充不同长度的pandas Dataframe列

[英]Fill pandas Dataframe columns of different length with a loop

This is an example of what I would like to do: 这是我想做的一个例子:

history=Dataframe()

range= 40
for k in range (range):

    epochs=k+1
    loss=np.random.rand(k+1,1)


history[k]=loss

This fills the Dataframe with k columns, with the loss array. 这将用loss列将k列填充到Dataframe中。

The problem is that, for the following iteration, loss is bigger than in the previous iteration, and bigger in the following. 问题在于,对于随后的迭代, loss要大于先前的迭代,而在之后的迭代中, loss更大。

So, there is a conflict between the dataframe index: 因此,数据框索引之间存在冲突:

raise ValueError('Length of values does not match length of ' 'index')
ValueError: Length of values does not match length of index

Is there any way to fill the dataframe as I want without this problem? 有什么办法可以填补我想要的数据框而不会出现此问题?

If the dataframe wasn't filled with a loop, I would think of filling it with NaNs. 如果数据框没有填充循环,我会考虑用NaN填充它。

Is this what you want ? 这是你想要的吗 ?

l= 3
for k in range(l):

    epochs=k+1
    loss=np.random.rand(k+1,1)
    if k ==0:
        history=pd.DataFrame(loss)
    else:
        history=pd.concat([history,pd.DataFrame(loss)],axis=1)
history.columns=range(3)

history
          0         1         2
0  0.043321  0.882806  0.578819
1       NaN  0.216240  0.558565
2       NaN       NaN  0.739184

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

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