简体   繁体   中英

replace dataframe header before printing

I have a csv that looks like:

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)

However, I want to display the df as: (custom header)

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)

Also, at last I'd like to write this df to a new csv file that hopefully looks like this:

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. (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.

But I cannot change the first(existing) csv file.

How do i achieve this?

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

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

Then write to csv

df.to_csv('newfile.csv')

To change col name:

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

To drop col:

del df['column_name']

To print to CSV:

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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