2017-08-02 51 views
1

對不起,基本的問題,但我似乎無法弄清楚。我有以下數據框:在數據框中重複一個元素

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 

我試圖用祿來無濟於事:

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 

回答

2

你可以做這種方式,使用pd.concat,然後sort_index

pd.concat([df,df.loc[[37]]]).sort_index().reset_index(drop=True) 

輸出:

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

@codeninja,'pd.concat([df,df.loc [[37] * 2]])。sort_index()。reset_index(drop = True)' – MaxU

+0

This works!我試圖使用某種插入/附加功能,但是你能解釋這條線的運行方式嗎? – codeninja

+1

@MaxU好評。謝謝。 –

3

你可以使用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)。