如何将列表添加到Pandas DataFrame?多种尝试均失败问题求助
问题原因与解决方案
核心问题
你首先存在两个基础错误导致所有插入方法失效:
- 字段长度不匹配:你定义的表头
head共14个字段,但是你构造的currentTicker列表多插入了1个beta字段,总长度15,和DataFrame列数不一致,所有插入操作都会触发长度不匹配报错,而你的外层try-except直接吞掉了报错信息,你看不到具体错误原因。 - 你注释的三个方法本身也存在用法错误:
df.append(currentTicker):首先pandas 1.4+版本已经正式弃用append方法,其次该方法不会修改原DataFrame,而是返回新对象,你没有赋值给df本身自然不会生效,且直接传入列表会被识别为逐行插入单个值,不是插入整行。df.loc[df_length] = currentTicker:该方法本身是可行的,但触发了上述字段长度不匹配的错误,无法执行。- 转Series的方法同样因为值长度和索引(df列数)长度不匹配直接报错。
此外你的代码还存在其他语法问题:
- 导入行
import helperFunctions import pandas语法错误,需要拆分为两行 - 打开
watchlist.txt后未主动关闭,建议用with上下文管理器处理文件读取 print(str(currentTicker + "\n"))写法错误,列表不能直接和字符串相加,会触发类型错误
修正方案
优先推荐你先把所有股票数据存到列表中,最后一次性转DataFrame,避免循环插入DataFrame的性能损耗:
import pandas as pd import helperFunctions # 读取股票代码 tickers = [] with open("watchlist.txt", "r") as f: for line in f: # 去掉换行符避免接口调用失败 tickers.append(helperFunctions.getTicker(line.strip())) # 表头加Beta字段,和数据长度对齐 head = ["Name", "Growth", "Recommendation", "Earnings Growth", "Current Ratio", "Total Cash", "Debt", "Revenue", "Percentage Shares Out", "Percentage Institutions", "Percentage Insiders", "Price to Book", "Short Ratio", "Beta", "Regular Market Price"] # 存储所有行数据的列表 all_data = [] try: for i in tickers: currentTicker = [] currentTicker.append(i.info['longName']) currentTicker.append(i.info['revenueGrowth']) currentTicker.append(i.info['recommendationKey']) currentTicker.append(i.info['earningsGrowth']) currentTicker.append(i.info['currentRatio']) currentTicker.append(i.info['totalCash']) currentTicker.append(i.info['totalDebt']) currentTicker.append(i.info['totalRevenue']) currentTicker.append(i.info['sharesPercentSharesOut']) currentTicker.append(i.info['heldPercentInstitutions']) currentTicker.append(i.info['heldPercentInsiders']) currentTicker.append(i.info['priceToBook']) currentTicker.append(i.info['shortRatio']) currentTicker.append(i.info['beta']) currentTicker.append(i.info['regularMarketPrice']) print(currentTicker) # 先加入总列表 all_data.append(currentTicker) except Exception as e: print(f"{i} 报错:{repr(e)}") # 一次性生成DataFrame df = pd.DataFrame(all_data, columns=head) print(df)
如果你一定要用循环插入的方式,修正长度问题后,用df.loc[len(df)] = currentTicker即可正常执行。
内容的提问来源于stack exchange,提问作者user13800925
相关产品推荐
相关产品推荐

