![](/img/trans.png)
[英]Why pandas dataframe displaying column names as 'unnamed: 1', unnamed: 2',.......'unnamed: n'
[英]Python/Pandas - Remove the first row with Unnamed: 0,Unnamed: 1,Unnamed: 2,Unnamed: 3,Unnamed: 4,Unnamed: 5,Unnamed: 6,Unnamed: 7
我正在將一個 xlsm 文件(包含多張紙)拆分為一個 csv,每張紙作為一個單獨的 csv 文件。 在此過程中,我刪除了前 4 行並僅保留從第 5 行開始的 header。這是輸入文件
這是我期望的 output -
但我得到以下 output -
這是我正在使用的代碼 -
import pandas as pd
xl = pd.ExcelFile('Sample_File.xlsm')
for sheet in xl.sheet_names:
df = pd.read_excel(xl,sheet_name=sheet)
df1 = df.iloc[3:]
df1.to_csv(f"{sheet}.csv",index=False)
如何刪除第一行的值從 unnamed: 0 到 unnamed: 9?
另外,我怎樣才能讓 comment1 出現在最后一列的(第一行和第二行)和 comment2 的(第三行和第四行)中?
您需要在pd.read_excel
function 中使用skiprows
參數才能正確獲取第 5 行中的列名。
更新包括前向填充
import pandas as pd
xl = pd.ExcelFile('Sample_File.xlsm')
for sheet in xl.sheet_names:
df = pd.read_excel(xl, sheet_name=sheet, skiprows=4) # no more iloc here
df['Comment'] = df['Comment'].ffill()
df.to_csv(f'{sheet}.csv', index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.