使用python将sheet2中出现次数为的关键字添加到sheet1的现有excelfile中

2024-05-26 21:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas将数据从web提取到excel工作表中并能够将其保存到工作表1中,现在我想将特定列的数据提取到同一excel的工作表2中,但只想输入关键字的名称以及该关键字在该列中出现的次数

例如,我在第一张表中有一个标题为“汽车制造商”的列,可以有多行数据不同,但同一个汽车制造商(如许多客户)可以拥有奥迪、福特等,第一张表中有6-7列,汽车制造商就是其中之一。我想得到如下数据

   Manufacturer Count
 1. Audi        100
 2. Ford        30
 3. Mercedes    25
 4. xxxxx       9

在第2页。 Python代码示例将不胜感激!你知道吗


Tags: 数据名称web标题pandas客户count关键字
2条回答

正如Stefan所回答的,在指定的列上使用value_counts()就可以了。你知道吗

由于要将多个数据帧保存到一个工作簿中,因此我将使用pandas.ExcelWriter

import pandas as pd

writer = pd.ExcelWriter('file_name.xlsx')
df.to_excel(writer)    # this one writes to 'Sheet1' by default
pd.Series.to_frame(df.Manufacturer.value_counts()).to_excel(writer, 'Sheet2')
writer.save()

不必使用openpyxl。如^{}文档所述

If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different DataFrames to one workbook

注意,为了使用to_excel(),必须将Series(从value_counts()返回)强制转换为DataFrame。这可以如上所述(通过to_frame())或通过使用:

pd.DataFrame(df.Manufacturer.value_counts()).to_excel(writer, 'Sheet2')

虽然第一个通常要快一点,但第二个可能被认为更具可读性。你知道吗

您向similar question询问了向第二个excel工作表添加数据的问题。也许您可以解决to_excel()部分的任何问题。你知道吗

在类别计数上,您可以执行以下操作:

df.Manufacturer.value_counts().to_frame()

counts得到pd.Series。您需要转换结果.to_frame(),因为只有DataFrameto_excel()方法。你知道吗

总之,使用我的链接答案:

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)
df.Manufacturer.value_counts().to_frame().to_excel(writer, sheet_name='Categories')
writer.save()

相关问题 更多 >

    热门问题