Python将空间删除列表转换为具有单个列的数据帧

2024-10-04 07:24:57 发布

您现在位置: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)

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


Tags: 数据方法fromimport名称df列表search
1条回答
网友
1楼 · 发布于 2024-10-04 07:24:57

尝试拆分列表中的每个字符串,并使用该字符串生成数据帧。 对于当前示例,您需要找到要拆分的正确字符,即“\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)

PS:记住关闭你的webdriver

相关问题 更多 >