【问题标题】:How to split the words in one column then integrate the words together in Python, i.e., two dimensional list to one dimensional list?如何将一列中的单词拆分然后在Python中将单词整合在一起,即二维列表到一维列表?
【发布时间】:2019-12-14 15:07:22
【问题描述】:

我的数据是:

a=pd.DataFrame({'sentences':['i am here','bye bye','go back home quickly']})

当我使用 split 时,我可以将字符串转换为单个单词:

a.loc[:,'sentences1']=a.loc[:,'sentences'].astype(str).str.split(' ')

结果是:

              sentences                 sentences1
0             i am here              [i, am, here]
1               bye bye                 [bye, bye]
2  go back home quickly  [go, back, home, quickly]

现在,我想将列表整合到“sentences1”列中,然后删除重复项。所以它看起来像:

[i, am, here, bye, go, back, home, quickly]

我该怎么做?

【问题讨论】:

    标签: string pandas list split


    【解决方案1】:

    您可以使用itertools.chain.from_iterable 将列表列表与dict.keys 扁平化以消除欺骗并维护秩序:

    import itertools
    [*itertools.chain.from_iterable([dict.fromkeys(i.split()).keys() for i in a.sentences])]
    

    或者使用OrderedDict:

    from collections import OrderedDict
    [*itertools.chain.from_iterable([OrderedDict.fromkeys(i.split()).keys() 
                                                    for i in a.sentences])]
    

    ['i', 'am', 'here', 'bye', 'go', 'back', 'home', 'quickly']
    

    【讨论】:

    • 酷!非常感谢。
    猜你喜欢
    • 2020-02-04
    • 2017-05-06
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-11-18
    • 2023-02-19
    相关资源
    最近更新 更多