【发布时间】:2019-12-01 22:58:13
【问题描述】:
我在下面有一个数据框:
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)
谢谢。
【问题讨论】:
-
对于初学者,永远不要在循环中附加数据帧。将您的结果累积到一个列表中,然后将它们连接到最后。
-
我想问一下,你最初是怎么得到第一个数据帧的?如果您的数据框中有列表,那么您当时可能不应该使用数据框
-
DataFrame 是从该结构中的某个来源提供的。
-
“从源头”是什么意思?
-
@juanpa.arrivillaga 你应该告诉他为什么他不应该在循环中追加。
标签: python pandas list dataframe flatten