【发布时间】:2021-12-17 18:23:58
【问题描述】:
我有这个数据框
df=
ID join Chapter ParaIndex text
0 NaN 1 0 I am test
1 NaN 2 1 it is easy
2 1 3 2 but not so
3 1 3 3 much easy
我想要这个
(合并列“join”中具有相同索引的“text”列并重新索引“ID”和“ParaIndex”,其余不变)
dfEdited=
ID join Chapter ParaIndex text
0 NaN 1 0 I am test
1 NaN 2 1 it is easy
2 1 3 2 but not so much easy
我用过这个命令
dfedited=df.groupby(['join'])['text'].apply(lambda x: ' '.join(x.astype(str))).reset_index()
它只合并列连接中具有数字索引的行并排除非索引的行
所以我改成了这个
dfedited=df.groupby(['join'],dropna=False)['text'].apply(lambda x: ' '.join(x.astype(str))).reset_index()
这里它基于索引连接合并所有行,但它将索引为 NaN 的行视为一个组,因此将它们也加入一组!但是,我不想加入他们……有什么想法吗?非常感谢
我也用过这个
dfedited=df.groupby(['join', "ParaIndex", "Chapter"],dropna=False )['text'].apply(lambda x: ' '.join(x.astype(str) )).reset_index()
它看起来更好,因为它包含所有列,但没有变化!
【问题讨论】:
-
我做到了! ``` dfedited=df.groupby(['join', "ParaIndex", "Chapter"],dropna=False )['text'].apply(lambda x: ' '.join(x.astype(str) ) ).reset_index() ```它不起作用
-
你完成了吗?为了方便起见,我建议至少提供一些可执行的东西。
-
是的,看看我的例子