简体   繁体   English

打印前更换 dataframe header

[英]replace dataframe header before printing

I have a csv that looks like:我有一个 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

When i read it and print it to terminal using:当我阅读并使用以下命令将其打印到终端时:

df = pd.read_csv('some3.csv',index_col=0)
print(df)

I get:我得到:

       bookName author  year genre  bookCount
bookId
1         book1    au1  1989  gen1         89
2         book2    au2   788  gen2         55
3         book3    au3  9799  gen1          7

(Notice that bookId comes in a different line, if someone could explain that as well, it'd be helpful since I am a beginner) (请注意 bookId 出现在不同的行中,如果有人也可以解释这一点,因为我是初学者,这会很有帮助)

However, I want to display the df as: (custom header)但是,我想将 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

And sometimes like: (without genre column)有时像:(没有流派列)

Book ID  Book Name  Author  Published Year  Book Count
1        book1      au1     1989            89
2        book2      au2     788             55
3        book3      au3     9799            7

(By replacing header with a custom one, and sometimes omit a few columns if required) (通过用自定义替换 header ,有时如果需要省略几列)

Also, at last I'd like to write this df to a new csv file that hopefully looks like this:另外,最后我想把这个 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

I'm open to adding a few parameters to pd.read_csv() to replace the header.我愿意向 pd.read_csv() 添加一些参数来替换 header。 (or change this statement entirely if necessary). (或在必要时完全更改此声明)。

I'm also fine with creating a new df to copy values and add a custom header, or any other code adjustments.我也可以创建一个新的 df 来复制值并添加自定义 header 或任何其他代码调整。

But I cannot change the first(existing) csv file.但我无法更改第一个(现有的)csv 文件。

How do i achieve this?我如何实现这一目标?

When you read the 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

Then replace the column with rename然后用rename替换列

df = df.rename(columns={'bookId' : 'Book ID',  ....})

Then write to csv然后写入 csv

df.to_csv('newfile.csv')

To change col name:要更改 col 名称:

df = pd.DataFrame({'aa':[1,3], 'bb': [13,20]})
df.columns = ['a', 'b']
df

To drop col:删除 col:

del df['column_name']

To print to CSV:要打印到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM