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

2024-04-19 00:38:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何基于dataframe中的一行创建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 

Tags: andofto数据dataframe数量createthis
2条回答

我正在使用repeat和{}

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 

我只重复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

根据评论,请尝试:

^{pr2}$

相关问题 更多 >