Skip to main content
 首页 » 编程设计

python之在数据框中重复一个元素

2025年05月04日23zlslch

很抱歉这个基本问题,但我似乎无法弄清楚。我有以下数据框:

df1 
      a               
1     7            
2     26              
3     32             
4     41              
...    
37    7 
38    9   

我将如何重复第 37 个索引处的值两次,以便生成以下内容

df1 
      a               
1     7            
2     26              
3     32             
4     41              
...    
37    7 
38    7 
39    9 

我试过使用 loc 无济于事:

 newp = df1[name].loc[np.repeat(df1.index[-2:].values, 1)] #get the 37th index value to repeat 
 listofwty[0].loc[36] = newp 
 listofwty[0].index = listofwty.index+1 

请您参考如下方法:

你可以使用 df.index.insert插入另一个条目 37,然后使用 df.reindex复制行:

import pandas as pd 
df = pd.DataFrame({'a': [7, 26, 32, 41, 7, 9]}, index=[1, 2, 3, 4, 37, 38]) 
index = df.index 
df = df.reindex(index.insert(index.get_loc(37), 37)) 
print(df) 

产量

     a 
1    7 
2   26 
3   32 
4   41 
37   7 
37   7 
38   9 

请注意,这将创建一个具有非唯一索引的 DataFrame。制作索引标签 唯一,调用 df = df.reset_index(drop=True)(如他的回答中的 Scott Boston showed)。