python---deel with data by pandas

Original: http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files
Excel files
The read_excel() method can read Excel 2003 (.xls) and Excel 2007+ (.xlsx) files using the xlrd Python module. The to_excel() instance method is used for saving a DataFrame to Excel. Generally the semantics are similar to working with csv data. See the cookbook for some advanced strategies.

Reading Excel Files:
#Returns a DataFrame
pd.read_excel(‘path_to_file.xls’, sheet_name=‘Sheet1’)

ExcelFile class:
xlsx = pd.ExcelFile(‘path_to_file.xls’)
df = pd.read_excel(xlsx, ‘Sheet1’)

The ExcelFile class can also be used as a context manager :
with pd.ExcelFile(‘path_to_file.xls’) as xls:
df1 = pd.read_excel(xls, ‘Sheet1’)
df2 = pd.read_excel(xls, ‘Sheet2’)

data = {}
#For when Sheet1’s format differs from Sheet2
with pd.ExcelFile(‘path_to_file.xls’) as xls:
data[‘Sheet1’] = pd.read_excel(xls, ‘Sheet1’, index_col=None,na_values=[‘NA’])
data[‘Sheet2’] = pd.read_excel(xls, ‘Sheet2’, index_col=1)

#equivalent using the read_excel function
data = {}
data = pd.read_excel(‘path_to_file.xls’, [‘Sheet1’, ‘Sheet2’], index_col=None, na_values=[‘NA’])

Reading a MultiIndex:
read_excel can read a MultiIndex index, by passing a list of columns to index_col and a MultiIndex column by passing a list of rows to header. If either the index or columns have serialized level names those will be read in as well by specifying the rows/columns that make up the levels.

Writing Excel Files:
To write a DataFrame object to a sheet of an Excel file, you can use the to_excel instance method. The arguments are largely the same as to_csv described above, the first argument being the name of the excel file, and the optional second argument the name of the sheet to which the DataFrame should be written. For example:

df.to_excel(‘path_to_file.xlsx’, sheet_name=‘Sheet1’)

with pd.ExcelWriter(‘path_to_file.xlsx’) as writer:
df1.to_excel(writer, sheet_name=‘Sheet1’)
df2.to_excel(writer, sheet_name=‘Sheet2’)

Writing Excel Files to Memory:

Pandas supports writing Excel files to buffer-like objects such as StringIO or BytesIO using ExcelWriter.

#Safe import for either Python 2.x or 3.x
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO

bio = BytesIO()

#By setting the ‘engine’ in the ExcelWriter constructor.
writer = pd.ExcelWriter(bio, engine=‘xlsxwriter’)
df.to_excel(writer, sheet_name=‘Sheet1’)

#Save the workbook
writer.save()

#Seek to the beginning and read to copy the workbook to a variable in memory
bio.seek(0)
workbook = bio.read()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值