【问题标题】:How can I combine the texts with same date in the python dataframe?如何在 python 数据框中组合具有相同日期的文本?
【发布时间】:2020-09-10 18:30:06
【问题描述】:

我有以下数据框,我想在一个日期收集具有相同日期的文本。

date        text
2020-09-10  text1
2020-09-10  text2
2020-09-09  text3
2020-09-09  text4
2020-09-08  text5
2020-09-08  text6

我预期的数据框是这样的。

date        text
2020-09-10  text1text2
2020-09-09  text3text4
2020-09-08  text5text6

【问题讨论】:

  • 分组,列,连接。你为什么要这样做?我不知道
  • 试试df.groupby('date')['text'].sum()

标签: python pandas dataframe concatenation multiple-columns


【解决方案1】:

这应该可以解决问题。

import numpy as np
import pandas as pd

df = pd.DataFrame({'date': ['2020-09-10','2020-09-10','2020-09-09','2020-09- 
09','2020-09-08','2020-09-08'],'text':['134','13','2','3','4','5']})
df.groupby('date')['text'].sum()

【讨论】:

  • 感谢您的建议,它以“系列”的形式返回。
【解决方案2】:

df.groupby('date').agg({'text':'sum'})

date        text
2020-09-10  text1text2
2020-09-09  text3text4
2020-09-08  text5text6

【讨论】:

  • 谢谢!这正是我想要的。此外,它作为数据框返回。
  • 不,这很有用。
  • 如果这回答了您的问题,请接受答案,以便可以关闭此问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2019-11-11
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 2021-07-18
  • 2021-08-01
相关资源
最近更新 更多