【问题标题】:Concatenating a series of strings into a single string within a Pandas Dataframe column (for each row)?将一系列字符串连接成 Pandas Dataframe 列中的单个字符串(对于每一行)?
【发布时间】:2021-05-12 05:02:06
【问题描述】:

这真的让我陷入了困境。在熊猫数据框(df)中,我有以下内容:

date News
2021-02-03 Some random event occurred today.
2021-02-03 We asked a question on Stack Overflow.
2021-02-02 The weather is nice.
2021-02-02 Hello. World.

日期列是日期格式的索引,新闻列是字符串。我想要做的是合并重复的日期并加入或连接新闻列,例如:

date News
2021-02-03 Some random event occurred today. We asked a question on Stack Overflow.
2021-02-02 The weather is nice. Hello. World.

到目前为止,我有:

df = df.groupby(['date']).agg({'News': list})

然而,虽然这确实结合了重复的日期,但它会将字符串值放在一个列表中,或者更确切地说,根据我在尝试加入它们时遇到的错误,将它们放入一个系列中。在这一点上,我完全迷失了,任何能引导我找到正确的pythonic方式的提示/提示将不胜感激!

PS:如果可能的话,我想避免使用循环,因为这将需要多次解析大约 200k 条记录(作为函数)。如果有什么不同,我将在 News 列上使用 TextBlob 来执行情绪分析。

【问题讨论】:

  • df.groupby('date')['News'].agg(' '.join).
  • 该死的哈迪斯,是 .join 而不是:join 非常感谢!!

标签: python pandas string dataframe concatenation


【解决方案1】:

Quang Hoang完美地回答了这个问题!虽然我无法将其标记为可悲的答案 =(

df.groupby('date')['News'].agg(''.join)。 – Quang Hoang 2 月 8 日 15:08

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2018-12-18
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多