[英]replace dataframe header before printing
我有一個 csv 看起來像:
bookId,bookName,author,year,genre,bookCount
1,book1,au1,1989,gen1,89
2,book2,au2,788,gen2,55
3,book3,au3,9799,gen1,7
當我閱讀並使用以下命令將其打印到終端時:
df = pd.read_csv('some3.csv',index_col=0)
print(df)
我得到:
bookName author year genre bookCount
bookId
1 book1 au1 1989 gen1 89
2 book2 au2 788 gen2 55
3 book3 au3 9799 gen1 7
(請注意 bookId 出現在不同的行中,如果有人也可以解釋這一點,因為我是初學者,這會很有幫助)
但是,我想將 df 顯示為:(自定義標題)
Book ID Book Name Author Published Year Genre Book Count
1 book1 au1 1989 gen1 89
2 book2 au2 788 gen2 55
3 book3 au3 9799 gen1 7
有時像:(沒有流派列)
Book ID Book Name Author Published Year Book Count
1 book1 au1 1989 89
2 book2 au2 788 55
3 book3 au3 9799 7
(通過用自定義替換 header ,有時如果需要省略幾列)
另外,最后我想把這個 df 寫到一個新的 csv 文件中,希望看起來像這樣:
Book ID,Book Name,Author,Published Year,Genre,Book Count
1,book1,au1,1989,gen1,89
2,book2,au2,788,gen2,55
3,book3,au3,9799,gen1,7
我願意向 pd.read_csv() 添加一些參數來替換 header。 (或在必要時完全更改此聲明)。
我也可以創建一個新的 df 來復制值並添加自定義 header 或任何其他代碼調整。
但我無法更改第一個(現有的)csv 文件。
我如何實現這一目標?
當您閱讀 csv
df = pd.read_csv('some3.csv')
# when you flag index col, it will read the first column as index ,
# that is why it is lower than other header
然后用rename
替換列
df = df.rename(columns={'bookId' : 'Book ID', ....})
然后寫入 csv
df.to_csv('newfile.csv')
要更改 col 名稱:
df = pd.DataFrame({'aa':[1,3], 'bb': [13,20]})
df.columns = ['a', 'b']
df
刪除 col:
del df['column_name']
要打印到 CSV:
df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.