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

时间:2019-11-02 17:19:24

标签: python pandas dataframe rows connect

我想连接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]。因此,我将获得一个新的条目“ cd”。

最后,输出应为:

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,这样我才能得到一个大条目。

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

3 个答案:

答案 0 :(得分: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})

答案 1 :(得分: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']

答案 2 :(得分: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])

如果有条件,我还必须添加一些其他信息...但是对于上面的简化示例,代码可以正常工作。