仅复制列中每个值的第一行

duplicate only the first row for each value in a column

我有以下数据框:

fake = pd.DataFrame({"group" : ["A","A","A","B","B","B","B","B","C","C"], 
                     "num" : ['1','2','3','4','5','6','7','8','9','10']})

>>> A   num
0   A   1
1   A   2
2   A   3
3   B   4
4   B   5
5   B   6
6   B   7
7   B   8
8   C   9
9   C   10

我希望每个组只复制第一行,以便得到这样的结果:

>>> A   num
0   A   1
1   A   2
2   A   3
  **A   1**
3   B   4
4   B   5
5   B   6
6   B   7
7   B   8
  **B   4**
8   C   9
9   C   10
  **C   9**

当星星是我想要的新行时(仅复制第一行)

我怎么能做这样的事情?我认为需要某种条件复制,但不知道该怎么做。

一个想法是使用 lambda 函数 DataFrame.append:

df = fake.groupby('group').apply(lambda x: x.append(x.iloc[0])).reset_index(drop=True)
print (df)
   group num
0      A   1
1      A   2
2      A   3
3      A   1
4      B   4
5      B   5
6      B   6
7      B   7
8      B   8
9      B   4
10     C   9
11     C  10
12     C   9

或者您可以对第一行使用 DataFrame.drop_duplicates,通过最后的重复项更改索引,通过 DataFrame.append 添加到原始索引值并为正确的最后排序索引值职位:

idx = fake.drop_duplicates('group', keep='last').index
df = (fake.append(fake.drop_duplicates('group')
                      .set_index(idx))
          .sort_index(kind='mergesort')
          .reset_index(drop=True))
print (df)
   group num
0      A   1
1      A   2
2      A   3
3      A   1
4      B   4
5      B   5
6      B   6
7      B   7
8      B   8
9      B   4
10     C   9
11     C  10
12     C   9

使用DataFrame.groupby on column group and aggregate using first then use pd.concat将其与原始数据框连接起来,最后sort_values:

df = pd.concat([df, df.groupby('group', as_index=False).first()])\
              .sort_values('group', ignore_index=True)

结果:

   group num
0      A   1
1      A   2
2      A   3
3      A   1
4      B   4
5      B   5
6      B   6
7      B   7
8      B   8
9      B   4
10     C   9
11     C  10
12     C   9