重复数据帧中的元素

2024-10-01 00:29:33 发布

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

很抱歉问了个基本问题,但我好像搞不懂。我有以下数据帧:

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

Tags: theto数据namegetindexvaluenp
2条回答

您可以使用^{}插入另一个37的条目,然后使用^{}复制该行:

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

请注意,这将创建具有非唯一索引的数据帧。制作索引标签 独特的,叫df = df.reset_index(drop=True)(作为Scott Boston showed在他的答案)

您可以这样做,使用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

相关问题 更多 >