在特定列中创建重复行并更改值

6
如何根据数据框中的一行创建x个副本,并更改特定列中的单个或多个变量。然后将这些行添加到同一数据框的末尾。
  A B C D E F
0 1 1 0 1 1 0
1 2 2 1 1 1 0
2 2 2 1 1 1 0
3 2 2 1 1 1 0
4 1 1 0 1 1 0 <- Create 25 Duplicates of this row (4) and change variable C to 1
5 1 1 0 1 1 0
6 2 2 1 1 1 0
7 2 2 1 1 1 0
8 2 2 1 1 1 0 
9 1 1 0 1 1 0 
2个回答

7
我只重复10次以保持结果长度合理。
#    Number of repeats |
#                      v
df.append(df.loc[[4] * 10].assign(C=1), ignore_index=True)

    A  B  C  D  E  F
0   1  1  0  1  1  0
1   2  2  1  1  1  0
2   2  2  1  1  1  0
3   2  2  1  1  1  0
4   1  1  0  1  1  0
5   1  1  0  1  1  0
6   2  2  1  1  1  0
7   2  2  1  1  1  0
8   2  2  1  1  1  0
9   1  1  0  1  1  0
10  1  1  1  1  1  0
11  1  1  1  1  1  0
12  1  1  1  1  1  0
13  1  1  1  1  1  0
14  1  1  1  1  1  0
15  1  1  1  1  1  0
16  1  1  1  1  1  0
17  1  1  1  1  1  0
18  1  1  1  1  1  0
19  1  1  1  1  1  0

根据评论,尝试以下操作:
df.append(df.loc[[4] * 10].assign(**{'C': 1}), ignore_index=True)

仅当文本长度足够短时才进行翻译。谢谢。 - piRSquared
如果它确实是 'C',那么它应该按照我所写的方式工作。如果它是由空格打断的短语,那么我们需要进行轻微更改。请告诉我实际的列名是什么。 - piRSquared
@Victor 我已经更新了帖子,提供了另一种选择。在这个例子中,将 'C' 替换为 '无论我的列名是什么' - piRSquared
@piRSquared 我的朋友。这是一些黑魔法。每个评论都让它工作了。 - user9238790
在当前版本的Pandas中,.append()已被弃用。推荐的方法是使用pd.concat(),这将使上面的示例看起来像df = pd.concat([df, df.loc[[4] * 10].assign(**{'C': 1})]) - Tom Johnson
显示剩余2条评论

2

我正在使用repeatreindex

s=df.iloc[[4],] # pick the row you want to do repeat
s=s.reindex(s.index.repeat(45))# repeat the row by the giving number 
#s=pd.DataFrame([df.iloc[4,].tolist()]*25) if need enhance the speed , using this line replace the above
s.loc[:,'C']=1 # change the value
pd.concat([df,s]) #append to the original df 

每一步发生了什么。 - user9238790
1
@Victor 添加解释 - BENY
谢谢@wen,我很感激朋友! - user9238790
@Victor yw :-) 祝你编程愉快 - BENY
索引不会改变,但似乎索引也被复制了,而不是从数据框中的最后一个索引继续。 - user9238790
@Victor,对我来说保留原始索引更有价值,因为我们可以轻松使用 reset_index() 获取新的索引。 :-) - BENY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接