gpt4 book ai didi

Python df.to_excel() 在 excel 中将数字存储为文本。如何存储为值?

转载 作者:太空狗 更新时间:2023-10-29 22:07:33 25 4
gpt4 key购买 nike

我正在通过 pd.read_html 从 google finance 抓取表格数据,然后通过 df.to_excel() 将该数据保存到 excel,如下所示:

    dfs = pd.read_html('https://www.google.com/finance?q=NASDAQ%3AGOOGL&fstype=ii&ei=9YBMWIiaLo29e83Rr9AM', flavor='html5lib')
xlWriter = pd.ExcelWriter(output.xlsx, engine='xlsxwriter')

for i, df in enumerate(dfs):
df.to_excel(xlWriter, sheet_name='Sheet{}'.format(i))
xlWriter.save()

但是,保存到 excel 中的数字存储为文本,单元格角上带有绿色小三角形。将此数据移至 excel 时,如何将它们存储为实际值而不是文本?

最佳答案

除了在创建或使用数据框时将字符串数据转换为数字的其他解决方案之外,还可以使用 xlsxwriter 引擎的选项来完成此操作:

# Versions of Pandas >= 1.3.0:
writer = pd.ExcelWriter('output.xlsx',
engine='xlsxwriter',
engine_kwargs={'options': {'strings_to_numbers': True}})

# Versions of Pandas < 1.3.0:
writer = pd.ExcelWriter('output.xlsx',
engine='xlsxwriter',
options={'strings_to_numbers': True})

来自docs :

strings_to_numbers: Enable the worksheet.write() method to convert strings to numbers, where possible, using float() in order to avoid an Excel warning about "Numbers Stored as Text".

关于Python df.to_excel() 在 excel 中将数字存储为文本。如何存储为值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com