简体   繁体   中英

How do I rename column names that have Parenthesis and Quotes?

I have 2 dataframes, A and B. I use some commands in A to get a pivot_table (and I used aggfunc to get total of 'Duration' data). After this, I merge A and B. When I run a command to show columns name, columns from A look strange, with parenthesis and quotes, like showed below: Index([ ('Name', ''), ('Code', ''), ('sum', 'Duration'), 'Position'], dtype='object')

Header example:

 <table border="1"> <tr> <td>('Name', '')</td> <td>('Code', '')</td> <td>('Sum', 'Duration')</td> <td>Position</td> </tr> </table> 

As you can see, only Position (which is from dataframe B). I tried to use rename function to change those 3 columns from A, but it didn't work.

What I expected to have as final was:

 <table border="1"> <tr> <td>Name</td> <td>Code</td> <td>Duration</td> <td>Position</td> </tr> </table> 

Does anybody know what kind of syntax I should use to rename those columns? Actually I save the file as csv and then I need to change the column names manually.

Use df.rename(columns=your_column_mapping) , like this:

df.rename(columns={"('Name', '')" : "Name",
                   "('Code', '')" : "Code",
                   "('Sum', 'Duration')" : "Duration"}) 

However, just like the others told you in the comments, you really should investigate how these weird names were generated in the first place.

Documentation of the rename method can be found here .

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