【问题标题】:Combine multiple lists resulting from a loop组合由循环产生的多个列表
【发布时间】:2020-03-01 17:49:55
【问题描述】:

我正在解析来自多个 html 的元素。

我正在以多个列表的形式得到答案。

这是我的代码的一部分:

for index, row in df.iterrows():
    r = driver.get(row['post'])                               
    soup = BeautifulSoup(r, "html.parser")
    records = []  
    comm = [r.nextSibling for r in soup.find_all('div', 
    class_=re.compile('_2b05'))]
    data = [''.join(i.stripped_strings) for i in comm if i]
    records.append(data)
    print(records)



    >>>> [['a', 'b', 'c', 'd']] [['x', 'y']]

这个公式在 for 循环下运行。 由于某种原因,它不会将所有列表附加到记录列表中。我需要将所有“记录”列表合并到一个 DataFrame 中 - 或者 - 如果可能的话 - 将两个列表的所有元素合并到一个 DataFrame 中。

我试过了:

items = list(set(chain.from_iterable(records)))

df = pd.DataFrame({'comment': list(item for item in 
itertools.chain.from_iterable(records))})

当我希望将它们组合成一个可以传输到 csv 的 DataFrame 时,两个结果都打印为两个单独的 DataFrame。

【问题讨论】:

  • 我试过records = [['a', 'b', 'c'], ['X', 'Y']],你的解决方案有效。能详细解释一下问题吗?
  • 我刚刚修改了我的问题。上面的代码在 for 循环下。但还是不明白为什么记录是 [['x','y','z']] 和 [['a','b','c']] 而不是 ['x','y' ,'z','a','b','c']
  • 你能把records的内容显示为代码吗?

标签: python python-3.x list dataframe


【解决方案1】:

可以使用函数from_records来实现 例如:

>>> records= [['a','b','c'],['x','y']]
>>> df = pd.DataFrame.from_records(records)
>>> df
   0  1     2
0  a  b     c
1  x  y  None

更新代码

>>> records= [[['a','b','c']],[['x','y']]]
>>> for i,item in enumerate(records):
...     if i==0:
...             df1 = pd.DataFrame.from_records(item)
...     else:
...             df1 = df1.append(item, ignore_index=True)
... 
>>> df1
   0  1    2
0  a  b    c
1  x  y  NaN

如果这有帮助,请告诉我!

【讨论】:

  • records 在 for 循环下,因此它将结果分为两个单独的列表,如下所示: = [['a','b','c'] [['x' ,'y']] 所以很遗憾你的答案不起作用
猜你喜欢
  • 2013-09-05
  • 2020-11-30
  • 2022-09-23
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2016-06-30
相关资源
最近更新 更多