2

我在下面有一个数据框:

import pandas
df = pandas.DataFrame({"terms" : [[['the', 'boy', 'and', 'the goat'],['a', 'girl', 'and', 'the cat']], [['fish', 'boy', 'with', 'the dog'],['when', 'girl', 'find', 'the mouse'], ['if', 'dog', 'see', 'the cat']]]})

我想要的结果如下:

df2 = pandas.DataFrame({"terms" : ['the boy  and the goat','a girl and the cat',  'fish boy with the dog','when girl find the mouse', 'if dog see the cat']})

有没有一种简单的方法可以实现这一点,而不必使用 for 循环遍历每个元素和子字符串的每一行:

result = pandas.DataFrame()
for i in range(len(df.terms.tolist())):
    x = df.terms.tolist()[i]
    for y in x:
        z = str(y).replace(",",'').replace("'",'').replace('[','').replace(']','')
        flattened = pandas.DataFrame({'flattened_term':[z]})
        result = result.append(flattened)

print(result)

谢谢你。

4

1 回答 1

3

这当然不是避免循环的方法,至少不是隐含的。Pandas 不是为了将list对象作为元素处理而创建的,它可以出色地处理数字数据,并且可以很好地处理字符串。无论如何,您的基本问题是您pd.Dataframe.append在循环中使用,这是一种二次时间算法(每次迭代都会重新创建整个数据帧)。但是您可能可以摆脱以下情况,并且应该会更快:

>>> df
                                               terms
0  [[the, boy, and, the goat], [a, girl, and, the...
1  [[fish, boy, with, the dog], [when, girl, find...
>>> pandas.DataFrame([' '.join(term) for row in df.itertuples() for term in row.terms])
                          0
0      the boy and the goat
1        a girl and the cat
2     fish boy with the dog
3  when girl find the mouse
4        if dog see the cat
>>>
于 2019-07-23T20:57:58.290 回答