从读取csv转换为excel-熊猫/ python

时间:2018-06-26 21:03:15

标签: python pandas

对此我是陌生的,所以对我好一点!

我有一些适用于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”值

我怎么了?

谢谢

1 个答案:

答案 0 :(得分:1)

似乎pd.read_csv('losstable.csv')用列的'str'加载csv。虽然df1 = pd.read_excel(xls, 'losstable')试图推断列的dtype。在这种情况下,它将列的dtype保留为int

从您的代码中删除此行:

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