Skip to main content
 首页 » 编程设计

python Pandas : Append rows of DataFrame and delete the appended rows

2025年05月04日24kevingrace

import pandas as pd 
df = pd.DataFrame({ 
    'id':[1,2,3,4,5,6,7,8,9,10,11], 
    'text': ['abc','zxc','qwe','asf','efe','ert','poi','wer','eer','poy','wqr']}) 

我有一个包含列的 DataFrame:

id    text 
1      abc 
2      zxc 
3      qwe 
4      asf 
5      efe 
6      ert 
7      poi 
8      wer 
9      eer 
10     poy 
11     wqr 

我有一个列表 L = [1,3,6,10],其中包含 ID 列表。

我正在尝试使用列表附加文本列,这样,从我的列表中首先取 1 和 3(列表中的前两个值)并在我的 DataFrame 中附加文本列 id = 1 其中有 id 的 2,然后删除具有 id 列 2 的行,然后采用 3 和 6,然后将 id = 4,5 的文本列附加到 id 3,然后删除 id = 4 和 5 的行并迭代列表 (x, x+1) 中的元素

我的最终输出是这样的:

id   text 
1    abczxc         # joining id 1 and 2 
3    qweasfefe      # joining id 3,4 and 5 
6    ertpoiwereer   # joining id 6,7,8,9 
10   poywqr         # joining id 10 and 11 

请您参考如下方法:

您可以使用 isin与 cumsum用于系列,用于 groupby使用 apply join 函数:

s = df.id.where(df.id.isin(L)).ffill().astype(int) 
df1 = df.groupby(s)['text'].apply(''.join).reset_index() 
print (df1) 
   id          text 
0   1        abczxc 
1   3     qweasfefe 
2   6  ertpoiwereer 
3  10        poywqr 

之所以有效,是因为:

s = df.id.where(df.id.isin(L)).ffill().astype(int) 
print (s) 
0      1 
1      1 
2      3 
3      3 
4      3 
5      6 
6      6 
7      6 
8      6 
9     10 
10    10 
Name: id, dtype: int32