Python将空间交付列表转换为具有单独列的数据帧



我正试图将列表转换为数据帧,但一直出错。

错误:ValueError:传递值的形状为(3,1(,索引表示(3,8(

之所以会出现这种情况,是因为第一列的名称中有时会有空格。有没有一种方法可以提取第一列,然后将其合并回来。这个列的名称中有空格,它混淆了列计数

from selenium import webdriver
from lxml import html
driver = webdriver.Chrome()
driver.get('https://finviz.com/futures.ashx')
search_deltaprice=[]
result_elements = driver.find_elements_by_xpath('//div[@class="tile_change pull-right"]/..')
for element in result_elements:
search_result = element.text
search_deltaprice.append(search_result)

df = pd.DataFrame(search_deltaprice, columns =['Ticker', 'Price', 'HighLabel','HighPrice','LowLabel','LowPrice','Change','PctChange'], dtype = str)

我试过这个:

df = pd.DataFrame(search_deltaprice)

但这返回了一个数据帧,其中有1列中的所有数据。我希望每个数据元素都在自己的列中,空格是分隔符。类型列表没有拆分方法。

尝试拆分列表中的每个字符串,并使用该字符串生成数据帧。对于当前示例,您需要找到要拆分的正确字符,即"\n">

driver.quit()
splitted_search=[x.split("n") for x in search_deltaprice]
df = pd.DataFrame(splitted_search, columns =['Ticker', 'Price', 'HighLabel','HighPrice','LowLabel','LowPrice','Change','PctChange'], dtype = str)

附言:记得关闭你的网络驱动程序。

相关内容

最新更新