【问题标题】:join rows with same index and keep other rows unchanged连接具有相同索引的行并保持其他行不变
【发布时间】: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() ```它不起作用
  • 你完成了吗?为了方便起见,我建议至少提供一些可执行的东西。
  • 是的,看看我的例子

标签: python dataframe nlp


【解决方案1】:

希望你能给出数据和代码的例子。一步一步地做,而不是只在一行中编写代码而不进行测试。这一行代码很难帮你。

但主要思想是使用merge(..., on='join')

【讨论】:

  • 谢谢,我用示例编辑我的问题...你能看看吗?
  • 你能详细说明一下吗?
【解决方案2】:

我就这样解决了;

dfEdited = df.assign(key=df['join'].ne(df['join'].shift()).cumsum()).groupby('key').agg({ "ParaIndex": 'first', "Chapter":'first','text':' '.join}).reset_index()

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2021-02-22
    • 2021-12-21
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2017-01-31
    相关资源
    最近更新 更多