【问题标题】:Fast way to expand a column of lists in pandas data frame to a single column将熊猫数据框中的一列列表扩展到单列的快速方法
【发布时间】:2019-12-01 15:57:50
【问题描述】:

我有一个数据框,其中包含与之对应的文本和情感分数。我创建了一个列,将所有二元组存储在一个列中。现在我想创建一个 Dataframe,它的这个 bigram 列扩展了它的分数,当我使用 for 循环执行第二步时,它的速度非常慢

enter image description here

enter image description here

【问题讨论】:

    标签: pandas


    【解决方案1】:

    熊猫 >= 0.25 您可以使用explode

    df = df.explode('bigrams')
    

    虚拟示例:

    import pandas as pd
    df1 = pd.DataFrame({'score':[0.2,0.3],
                   'bigrams':[['a', 'b', 'c', 'e'],['f','g']]})
    
    print(df1)
    

    ===========================

    df1:

        score   bigrams
    0   0.2     [a, b, c, e]
    1   0.3     [f, g]
    

    ============================

    df1 = df1.explode('bigrams')
    print(df1)
    

    ==============================

    df1:

        score   bigrams
    0   0.2     a
    0   0.2     b
    0   0.2     c
    0   0.2     e
    1   0.3     f
    1   0.3     g
    

    【讨论】:

    • 我收到以下错误:“DataFrame”对象没有属性“explode”
    • 更新你的熊猫版本。做pip install -U pandas
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多