2

I'm struggling on removing the index column from the dataframe.

Usually when I read a csv file, I can set the index = False or index_col = 0, and that removes the index column. But I can't do that when reading html for some reason. Any ideas? I've also tried reset_index(drop=True). I don't want to set any of the columns to an index.

path = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M' 

canada = pd.read_html(path)    

cn_table=canada[0]

1 Answer 1

2

IIUC , you want the 1st row as headers, Use header=0:

canada = pd.read_html(r'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M',header =0, flavor = 'bs4')

Or:

canada = pd.read_html(r'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M',header =0)

cn_table=canada[0]
>>cn_table

    Postcode    Borough          Neighbourhood
0   M1A         Not assigned     Not assigned
1   M2A         Not assigned     Not assigned
2   M3A         North York       Parkwoods
3   M4A         North York       Victoria Village
4   M5A         Downtown Toronto Harbourfront
5   M5A         Downtown Toronto Regent Park

... ... ... ...
288 M9Z         Not assigned     Not assigned

To save the dataframe to csv without index use:

cn_table.to_csv('path+filename.csv',index=False)
Sign up to request clarification or add additional context in comments.

8 Comments

The output still contains an index column.
@user10939484 can you share your expected output plz?
@user10939484 did you mean print(cn_table.to_string(index=False)) ??
No, I'd like to permanently modify the dataframe to output only the 3 columns without the index to the left. Same as your output without the index.
Thanks, I was not aware of that. Not bothering me. The assignment I'm working on has a finished dataframe image that does not have an index so it's been annoying me, making me think I was just missing something obvious.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.