【问题标题】:Adding sheet2 to existing excelfile from data of sheet1 with pandas python使用pandas python将sheet2从sheet1的数据添加到现有的excelfile
【发布时间】:2016-06-02 11:56:20
【问题描述】:

我正在使用 pandas 将数据从 Web 提取到 Excel 工作表中,并且能够将其保存到工作表 1,现在我想将列数据提取到相同 Excel 的工作表 2 中。

当我执行代码时,它仍然不会在 excelfile 中创建新工作表,只是用新名称和所需数据覆盖现有工作表。

我创建了两个函数,第一个函数创建包含所需数据的 excel 文件和函数 2 以获取列值并使用该列值创建新工作表

这是功能 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()

我还想获得表 2 中特定类别的计数。 请帮忙

样本数据

我已经在表格 2 中突出显示了我想要的数据,并且我想要表格 2 中每个类别的计数以及类别名称

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.

【问题讨论】:

  • 您可以添加数据样本(3,4 行)和所需的输出table1 吗?也可以使用table1 = df[['Category']],不需要循环。
  • @jezrael 我已经更新了示例数据

标签: python excel pandas


【解决方案1】:

您可以使用openpyxl,库pandas 用于xlsx,来实现:

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)

然后,准备好您的table1

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

writer.save()

【讨论】:

  • 感谢您的帮助。你能帮忙计算表 2 中每个类别的类别名称吗
  • IIUC 你只想提取完整的列Category?查看更新。
  • 不确定我是否理解您要查找的内容,您的问题标题要求在不覆盖的情况下将数据添加到第二张 Excel 工作表,但还有另一个关于 .value_counts() 的问题?但是,您的示例包含的信息不仅仅是类别计数吗?请参阅.value_counts() 的更新。
猜你喜欢
  • 1970-01-01
  • 2016-03-30
  • 2016-07-25
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多