如何使用 pandas 复制一行并将其直接追加到复制的行之后?

How can I duplicate a row and append it directly after the duplicated row using pandas?

我已经尝试解决这个问题几个小时了,但似乎每次都走到了死胡同。下面显示了我想要做的一个小例子。

Normal Series
a
b
c
d
Duplicated Series
a
a
b
b
c
c
d
d

您可以将重复的系列连接在一起并对其进行排序。

sample = pd.Series(['a','b','c','d'])
output = pd.concat([sample,sample]).sort_values().reset_index(drop=True)
output

试试 locdf.index.repeat:

>>> df.loc[df.index.repeat(2)]
  Normal Series
0             a
0             a
1             b
1             b
2             c
2             c
3             d
3             d
>>> 

reset_index:

>>> df.loc[df.index.repeat(2)].reset_index(drop=True)
  Normal Series
0             a
1             a
2             b
3             b
4             c
5             c
6             d
7             d
>>>