[英]How can I webscrape information in the html element and save it to an Excel row using Beautifulsoup and any excel writer(Pandas)?
[英]How can I insert an excel formula using pandas when I save it as an excel file?
我有以下帶有多個列和行的數據框,
A | B | C | D | E |....
2 | b | c | NaN | 1 |
3 | c | b | NaN | 0 |
4 | b | b | NaN | 1 |
.
.
.
有沒有辦法通過在輸出 excel 文件中使用 python 的示例以下面所述的方式添加 excel 公式(對於某些列)?
例如,我希望能夠有這樣的輸出,
=SUM(A0:A2) | | | | =SUM(E0:E2)
A | B | C | D | E
0 2 | b | c | =IF(B0=C0, "Yes", "No") | 1
1 3 | c | b | =IF(B1=C1, "Yes", "No") | 0
2 4 | b | b | =IF(B2=C2, "Yes", "No") | 1
.
.
.
最終輸出,
9 | | | | 2
A | B | C | D | E
0 2 | b | c | No | 1
1 3 | c | b | No | 0
2 4 | b | b | Yes | 1
.
.
.
我想在最終輸出的 excel 文件中添加公式,以便如果列的值(在最終輸出的 excel 文件中)有任何更改,其他列也可以在 excel 文件中實時更新,例如,
15 | | | | 3
A | B | C | D | E
0 2 | b | b | Yes | 1
1 9 | c | b | No | 1
2 4 | b | b | Yes | 1
.
.
.
例如,如果我將 A1 的值從 3 更改為 9,則列的總和更改為 15; 當我將C0的值從“c”改為“b”時,其對應的行值,即D0的值由“No”變為“Yes”; 對於 col E 也是如此。
我知道您可以使用 xlsxwriter 庫來編寫公式,但我無法弄清楚如何按照我在上面的示例中所述的方式添加公式。
任何幫助將不勝感激,提前致謝!
您最好通過xlsxwriter
而不是pandas
來xlsxwriter
您希望保留的所有公式。
如果您只想導出結果,您可以使用pandas
,因為您想保留公式,請在編寫電子表格時執行。
下面的代碼會將dataframe
和公式寫出到名為test
的xlsx
文件中。
import xlsxwriter
import pandas as pd
from numpy import nan
data = [[2, 'b', 'c', nan, 1], [3, 'c', 'b', nan, 0], [4, 'b', 'b', nan, 1]]
df = pd.DataFrame(data=data, columns=['A', 'B', 'C', 'D', 'E'])
## Send values to a list so we can iterate over to allow for row:column matching in formula ##
values = df.values.tolist()
## Create Workbook ##
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
## Iterate over the data we extracted from the DF, generating our cell formula for 'D' each iteration ##
for idx, line in enumerate(values):
d = f'=IF(B{row + 1}=C{row + 1}, "Yes", "No")'
a, b, c, _, e = line
## Write cells into spreadsheet ##
worksheet.write(row, col, a)
worksheet.write(row, col + 1, b)
worksheet.write(row, col + 2, c)
worksheet.write(row, col + 3, d)
worksheet.write(row, col + 4, e)
row += 1
## Write the total sums to the bottom row of the sheet utilising the row counter to specify our stop point ##
worksheet.write(row, 0, f'=SUM(A1:A{row})')
worksheet.write(row, 4, f'=SUM(E1:E{row})')
workbook.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.