熊猫-在while循环中向行添加多个值

时间:2019-07-11 01:52:55

标签: python pandas dataframe

我正在使用while循环内的数据帧,该数据帧需要根据仿真时间进行更新。这是一个示例:

import pandas as pd
import random

n = 0
df = pd.DataFrame(columns=['A', 'B'])

while n < 10:
  df = df.append({'A': random.uniform(0, 1), 'B': random.uniform(0, 1)}, 
                 ignore_index=True)
  df = df.append({'A': random.uniform(0, 1), 'B': random.uniform(0, 1)}, 
                 ignore_index=True)

  df['New Column'] = n

  print('This value should be added to the new rows only ' + str(n))
  n += 1
  print(df)

这会导致整个新列立即被更新,对于我而言,这是不希望的。这是前三张照片:

This value should be added to the new rows only 0
          A         B  New Column
0  0.242312  0.369978           0
1  0.709112  0.650794           0
This value should be added to the new rows only 1
          A         B  New Column
0  0.242312  0.369978           1    <- should have been 0
1  0.709112  0.650794           1    <- should have been 0
2  0.293787  0.229019           1
3  0.828184  0.917984           1
This value should be added to the new rows only 2
          A         B  New Column
0  0.242312  0.369978           2    <- should have been 0
1  0.709112  0.650794           2    <- should have been 0
2  0.293787  0.229019           2    <- should have been 1
3  0.828184  0.917984           2    <- should have been 1
4  0.644289  0.589050           2
5  0.371361  0.759865           2

我可以在一个操作中执行此操作,还是需要复制到另一个数据框然后附加它?

1 个答案:

答案 0 :(得分:1)

使用以下代码:

import pandas as pd
import random

n = 0
df = pd.DataFrame(columns=['A', 'B', 'New Column'])

while n < 10:
  df = df.append({'A': random.uniform(0, 1), 'B': random.uniform(0, 1), 'New Column': n}, 
                 ignore_index=True)
  df = df.append({'A': random.uniform(0, 1), 'B': random.uniform(0, 1), 'New Column': n}, 
                 ignore_index=True)

  print('This value should be added to the new rows only ' + str(n))
  n += 1
  print(df)

只需从一开始就有一个New Column,然后像在A内使用Bappend一样添加值,我就在制作{{ 1}}也位于相同的New Column中。

您的代码不起作用,因为您需要在每次循环时都修改 all 值,这是我正在做的事情,需要在附加数据帧中使用它。