如何在每次迭代中相对于索引替换列值,以便每个表在每次迭代中都具有新的一组值

时间:2018-06-30 12:13:25

标签: python dataframe

有人可以帮我吗?

   Index      word
0      0         I
1      1        am
2      2        so
3      3      good
4      4       and
5      5     smart  

 df_series=[]
 for d in range(0,2):
    df_series.append(df)

def pos(x):
    position=[]
    for u in x:
        position.append(np.random.choice(u[0]))
    return position

 two = [5,2]
 j = [1,0]
 df1=[]
 df1.append(pd.DataFrame(two))
 df1.append(pd.DataFrame(j))

df1

   0
0  5
1  2
   0
0  1
1  0

 final=[] 
 L=['NA','****']
 for eachtable in df_series:
 #  print(eachtable)
    eachtable.loc[pos(df1),'word'] = random.choice(L)
    final.append(eachtable)

final

 Index  word
       0    ****
       1    NA
       2    so
       3    good
       4    and
       5    NA

    Index   word
       0    ****
       1    NA
       2    so
       3    good
       4    and
       5    NA

到现在为止我只是这样。位置仅在第一个表中更改,并且在所有迭代中重复相同的位置。我想为每个迭代更改位置。任何人都可以在我的代码中找到错误并为此提供帮助。

我想要这样的东西

print(final)

Index   word
   0    ****
   1    NA
   2    so
   3    good
   4    and
   5    NA
Index   word
   0    I
   1    am
   2    ****
   3    good
   4    NA
   5    smart

1 个答案:

答案 0 :(得分:1)

问题在第一个循环中,列表中仍然引用相同的DataFrameSeries):

for eachtable in df_series:
    print (id(eachtable))
294921776
294921776

解决方案已添加copy

df_series=[]
for d in range(0,2):
    df_series.append(df.copy())

检查:

for eachtable in df_series:
    print (id(eachtable))
294987928
294922056

for eachtable in df_series:
    eachtable.loc[pos(df1),'word'] = random.choice(L)
    final.append(eachtable)

print (final)
[   Index   word
0      0     NA
1      1     am
2      2     NA
3      3   good
4      4    and
5      5  smart,    Index  word
0      0     I
1      1  ****
2      2    so
3      3  good
4      4   and
5      5  ****]