python - 在 Pandas Dataframe 中按天连接字符串列表

标签 python pandas

我有以下内容:

import pandas as pd
import numpy as np

documents = [['Human', 'machine', 'interface'],
             ['A', 'survey', 'of', 'user'],
             ['The', 'EPS', 'user'],
             ['System', 'and', 'human'],
             ['Relation', 'of', 'user'],
             ['The', 'generation'],
             ['The', 'intersection'],
             ['Graph', 'minors'],
             ['Graph', 'minors', 'a']]

df = pd.DataFrame({'date': np.array(['2014-05-01', '2014-05-02', '2014-05-10', '2014-05-10', '2014-05-15', '2014-05-15', '2014-05-20', '2014-05-20', '2014-05-20'], dtype=np.datetime64), 'text': documents})

只有 5 个不同的日子。我想按天分组以得到以下结果:

documents2 = [['Human', 'machine', 'interface'],
              ['A', 'survey', 'of', 'user'],
              ['The', 'EPS', 'user', 'System', 'and', 'human'],
              ['Relation', 'of', 'user', 'The', 'generation'],
              ['The', 'intersection', 'Graph', 'minors', 'Graph', 'minors', 'a']]


df2 = pd.DataFrame({'date': np.array(['2014-05-01', '2014-05-02', '2014-05-10', '2014-05-15', '2014-05-20'], dtype=np.datetime64), 'text': documents2})

最佳答案

IIUC,你可以通过sumaggregate

df.groupby('date').text.sum() # or .agg(sum)

date
2014-05-01                          [Human, machine, interface]
2014-05-02                                [A, survey, of, user]
2014-05-10                 [The, EPS, user, System, and, human]
2014-05-15                [Relation, of, user, The, generation]
2014-05-20    [The, intersection, Graph, minors, Graph, mino...
Name: text, dtype: object

或者使用列表理解来展平你的列表,它产生与 chain.from_iterable 相同的时间复杂度,但不依赖于一个额外的外部库

df.groupby('date').text.agg(lambda x: [item for z in x for item in z])

关于python - 在 Pandas Dataframe 中按天连接字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51576723/

相关文章:

python - BeautifulSoup(html) 不工作,说不能调用模块?

python - 删除 python pandas 中的 NaN 值

python - pandas 绘制聚合时间戳索引

pandas groupby 聚合,总和在底部

python - Ubuntu 18.04 上的 JModelica

python - 查找并删除多个文件中的重复内容

python - 根据输入文件内容创建多个命名管道(fifo)

python - 如何将我的数据框转换为二维列表,并将所有列作为列表

python - pandas 在数据框中找到两条线的交点

python - 如何对具有非数值的数据框进行分组和透视