【问题标题】:Regroup pandas column into 2D list based on another column根据另一列将 pandas 列重新组合为 2D 列表
【发布时间】:2019-11-29 09:02:31
【问题描述】:

我有一个 pandas 数据集,其中有一列单词和一列整数 (0,1)。所有出现在零(第一个整数,或在 1 之后)和 1(包括)之间的单词都应放入二维数组中。

让我解释一下:

考虑一下这个 pandas 数据框:

import pandas as pd

df = pd.DataFrame(columns=['Text','Selection_Values'])
df["Text"] = ["Hi", "this is", "just", "a", "single", "sentence.", "This", "is another one."]
df["Selection_Values"] = [0,0,0,0,0,1,0,1]
print(df)

这是示例数据集:

              Text  Selection_Values
0               Hi                 0
1          this is                 0
2             just                 0
3                a                 0
4           single                 0
5        sentence.                 1
6             This                 0
7  is another one.                 1

预期的结果应该是:

[["Hi this is just a single sentence."],["This is another one"]]

你知道怎么做吗?

这是我到目前为止所做的:

result = []

s = ""
for i in range(len(df["Text"])):
    s += df["Text"][i] + " "
    if df["Selection_Values"][i] == 1:
        result.append([s])
        s = ""

有效:

[['Hi this is just a single sentence. '], ['This is another one. ']]

...但这可能不是最好的方法。它根本不使用 pandas 框架。

【问题讨论】:

    标签: python python-3.x pandas list


    【解决方案1】:

    numpy.split + Series.str.cat 单线:

    In [143]: [[s.str.cat(sep=' ')] for s in np.split(df.Text, df[df.Selection_Values == 1].index+1) if not s.empty]                               
    Out[143]: [['Hi this is just a single sentence.'], ['This is another one.']]
    

    【讨论】:

    • 非常感谢您的回答!真的很酷,一个班轮!我意识到数据集的最后一句话可能没有结束语 1。您将如何处理?
    • @henry,它也适用于系列df["Selection_Values"] = [0,0,0,0,0,1,0,0](最后一个0
    • 太棒了!非常感谢!
    【解决方案2】:

    这是一种可能的方法:

    import pandas as pd
    
    # Initialize example dataframe
    df = pd.DataFrame(columns=['Text', 'Selection_Values'])
    df["Text"] = ["Hi", "this is", "just", "a", "single", "sentence.", "This", "is another one."]
    df["Selection_Values"] = [0, 0, 0, 0, 0, 1, 0, 1]
    
    # Add column with an unique group ID for each sentence
    df['group_id'] = df.Selection_Values.shift(1, fill_value=0).cumsum()
    
    # Join the strings that have the same group ID
    sentence_series = df.groupby('group_id')['Text'].agg(' '.join)
    
    # Optional: convert result series to list
    sentence_list = sentence_series.to_list()
    
    print(sentence_list)
    # Output:
    # ['Hi this is just a single sentence.', 'This is another one.']
    

    【讨论】:

    • 非常感谢您的回答!我意识到数据集的最后一句话可能没有结束语 1。您将如何处理?
    • @henry 代码解决方案也应该适用于这种情况(因为df.Selection_Values 的最后一个值无论如何都会被shift 操作丢弃)。
    【解决方案3】:

    使用shift + ' '.join。这当然假设每个句子都有一个结尾1,并且没有悬句。


    g = df['Selection_Values'].shift().eq(1).cumsum()
    
    df['Text'].groupby(g).agg(' '.join).tolist()
    

    ['Hi this is just a single sentence.', 'This is another one.']
    

    【讨论】:

    • 非常感谢您的回答!我意识到数据集的最后一句话可能没有结束 1。你会怎么处理这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2020-12-08
    • 2022-08-11
    • 2015-02-27
    • 2020-04-16
    • 2017-07-24
    相关资源
    最近更新 更多