python数据写入到excel不同sheet,使用pandas python从sheet1的数据中将sheet2添加到现有的excelfile中...

I am fetching data from web into an excel sheet using pandas & able to save it to sheet 1, now i want to fetch a column data into sheet 2 of same excel.

When I am executing the code it still doesn't create a new sheet in the excelfile, just overwrites the existing sheet with new name & desired data.

I have created two functions , first function create the excel file with desired data & function 2 to fetch the column values & create new sheet with that column values

This is Function 2

def excelUpdate():

xls_file = pd.ExcelFile('Abc.xlsx')

df = xls_file.parse(0)

data=[]

for i in df.index:

x=df['Category'][i]

print(df['Category'][i])

data.append(x)

table1 = pd.DataFrame(data)

table1.to_excel(writer, sheet_name='Categories')

writer.save()

Also I want to get the count of a particular category in sheet 2.

Please help

Sample data

I have highlighted the data which I want in sheet 2 & I want the count of each Category in sheet 2 with category name

Index | AppVersion | Author | **Category** | Description | Rating | Text

0 | 1.15 | Miuwu | **Slow** | Worthless | 1 | Worked fine while I was home, a week later and 3000 miles away nothing!!

1 | 1.15 | abc | **Problem** | Self-reboot | 1 | No such option.

2 | 1.15 | Rax | **Design** | Self-reboot | 1 | No such option.

3 | 1.15 | golo7 | **Problem** | Self-reboot | 1 | No such option.

4 | 1.15 | Marcog | **Problem** | Self-reboot | 1 | No such option.

解决方案

You can use openpyxl, the library pandas uses for xlsx, to achieve this:

import pandas as pd

from openpyxl import load_workbook

book = load_workbook('Abc.xlsx')

writer = pd.ExcelWriter('Abc.xlsx', engine='openpyxl')

writer.book = book

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

Then, with your table1 ready:

df['Category'].value_counts().to_frame().to_excel(writer, sheet_name='Categories')

writer.save()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值