如何连接 Pandas 数据框中的特定行?

问题描述 投票:0回答:3

我想连接 Pandas 数据框中的特定行。

我有一列“文本”和另一列“名称”。 “文本”列的每个条目都有一个字符串。 “名称”列的某些条目是空的,因此我想将“名称”列中具有空条目的第 n 行与行 (n-1) 连接起来。如果行 (n-1) 在“名称”列中也有一个空条目,则这些行应连接到在“名称”列中具有条目的下一行。

例如:
输入:

Text=["Abc","def","ghi","jkl","mno","pqr","stu"]

Name=["a","b","c",““,““,"f","g"]

预期输出:

Text= ["Abc","def","ghijklmno","pqr","stu"]

Name = ["a","b","c","f","g"]

我想让我的问题更容易理解:

我有两个清单:

index = [3,6,8,9,10,12,15,17,18,19]
text = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
new = []
for i in range(0,len(text)):
    if i not in index:
        if i+1 not in index:
            new.append(text[i])
    if i in index:
        new.append(text[i-1]+' '+ text[i])

列表索引显示文本的错误分割(当列名称没有值时)。 因此,我想附加例如文本[3]到文本[2]。所以我会得到一个新条目“c d”。

最后,输出应该是:

new = ['a','b,'c d','e','f g','hijk','lm','n','op','qrst','u','v','w','x','y','z']

这些列表只是我的大型文本列表的简化示例。我不知道有多少条目需要连接在一起。我的算法仅在必须将条目 n 与条目 n-1 连接时才有效。但也有可能我必须将条目 n 与 n-10 之前的条目连接起来,因此我得到一个大条目。

我希望我的问题现在更容易理解了。

python pandas dataframe row
3个回答
1
投票

NaN
和前向填充替换空字符串。然后
groupby
命名列并聚合。

import pandas as pd

df.Name = df.Name.str.replace('', pd.np.nan).ffill()
out_df = df.groupby('Name').agg({'Text': ' '.join})

0
投票

使用 defaultdict

   Name=["a","b","c",None,None,None,"f","g"]
    Text=["Abc","def","ghi","jkl","mno","pqr","stu"] 

    lst=list(zip(Name,Text))

    from collections import defaultdict 

    d=defaultdict(str) 


    for i, v in lst:
        d[i] += v

    print(list(d.values()))
['Abc', 'def', 'ghi', 'jklmnopqr', 'stu']

0
投票

我现在有了解决方案(代码看起来不太好,但输出是我期望的):

for i in range(0,len(text)):
    if i not in index:
        if i+1 not in index:
            new.append(text[i])
        elif i+1 in index:
            if i+2 not in index:
                new.append(text[i]+text[i+1])
            elif i+2 in index:
                if i+3 not in index:
                    new.append(text[i]+text[i+1]+text[i+2])
                elif i+3 in index:
                    if i+4 not in index:
                        new.append(text[i]+text[i+1]+text[i+2]+text[i+3])
                    elif i+4 in index:
                        if i+5 not in index:
                            new.append(text[i]+text[i+1]+text[i+2]+text[i+3]+text[i+4])

我必须添加更多 if 条件...但是对于上面的简化示例,代码可以完美运行。

© www.soinside.com 2019 - 2024. All rights reserved.