在数据框中重复一个元素

时间:2017-08-02 18:13:51

标签: python python-3.x pandas dataframe

对不起基本问题,但我似乎无法解决这个问题。我有以下数据框:

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

2 个答案:

答案 0 :(得分: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)。

答案 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