gpt4 book ai didi

python - 从读取 csv 转换为 excel - pandas/python

转载 作者:行者123 更新时间:2023-12-01 09:18:03 28 4
gpt4 key购买 nike

我是新手,所以请对我宽容一些!

我有一些代码可以很好地处理 CSV 文件,但我想将其转换为读取 Excel 文件,这样每个文件就可以有多个选项卡。

这是工作原件

import numpy as np
import pandas as pd
import csv
pd.options.mode.chained_assignment = None

#the whole portfolio
num_of_contracts = 1418
num_of_simul = 10000

contract_info_df = pd.read_csv('contract_info..csv', encoding='latin-1')
contract_info_df = contract_info_df.set_index(['Contract Identifier'])
toy_contract = contract_info_df.iloc[:num_of_contracts, :]
toy_contracts_list = contract_info_df.iloc[:num_of_contracts, :].index.tolist()
toy_contracts_list = (list(map(str, toy_contracts_list)))
toy_contract.index = toy_contracts_list



loss_df = pd.read_csv('losstable.csv')
loss_table = loss_df.loc[:,toy_contracts_list][:num_of_simul]
loss_table['row_sum'] = loss_table.sum(axis = 1)

这是我的尝试

import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None

#the whole portfolio
num_of_contracts = 162
num_of_simul = 10000

xls = pd.ExcelFile('contract_info.xlsx')
df1 = pd.read_excel(xls, 'contract_info') #worksheetname

contract_info_df = df1.set_index(['Contract Identifier'])
toy_contract = contract_info_df.iloc[:num_of_contracts, :]
toy_contracts_list = contract_info_df.iloc[:num_of_contracts, :].index.tolist()
toy_contracts_list = (list(map(str, toy_contracts_list)))
toy_contract.index = toy_contracts_list


xls = pd.ExcelFile('losstable.xlsx')
loss_df = pd.read_excel(xls, 'losstable') #woorksheet name
loss_table = loss_df.loc[:,toy_contracts_list][:num_of_simul]

错误出现在最后一行,它无法在[列]中找到“toy_contracts_list”值

我的问题是什么?

谢谢

最佳答案

看起来 pd.read_csv('losstable.csv')加载带有“str”列的 csv。而df1 = pd.read_excel(xls, 'losstable')尝试推断列的数据类型。在本例中,它将列的 dtype 保留为 int

从代码中删除此行:

toy_contracts_list = (list(map(str, toy_contracts_list)))

关于python - 从读取 csv 转换为 excel - pandas/python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051335/

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