[英]Python Pandas replace a cell containing a string with its above cell
[英]Insert a single cell of string above header row in python pandas
import pandas as pd
df = pd.DataFrame({'label':['first','second','first','first','second','second'],
'first_text':['how is your day','the weather is nice','i am feeling well','i go to school','this is good','that is new'],
'second_text':['today is warm','this is cute','i am feeling sick','i go to work','math is hard','you are old'],
'third_text':['i am a student','the weather is cold','she is cute','ii am at home','this is bad','this is trendy']})
df.loc[-1] = df.columns.values
df.sort_index(inplace=True)
df.reset_index(drop=True, inplace=True)
df.rename(columns=
{"label": "Register", 'first_text':'', 'second_text':'', 'third_text':''},
inplace=True)
試試這個MRE ,這樣你也可以改變你的數據。
您可以從第二行開始保存 dataframe,然后使用其他工具寫入 excel 文件的第一個單元格。
請注意,從 pandas 寫入 excel 會覆蓋其數據,因此我們必須遵循此順序(但也有一些方法可以寫入現有的 excel 數據而不覆蓋)。
1.保存 dataframe,指定startrow=1
:
df.to_excel("filename.xlsx", startrow=1, index=False)
2.寫一個單元格值。
例如,使用openpyxl
(來自GeeksforGeeks 教程):
from openpyxl import load_workbook
# load excel file
workbook = load_workbook(filename="filename.xlsx")
# open workbook
sheet = workbook.active
# modify the desired cell
sheet["A1"] = "A60983A Register"
# save the file
workbook.save(filename="filename.xlsx")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.