Why is KeyError error in attempting to contact the table column?
-
I want to get a list of towns from the Vikipedia and put them on the list.
I'm doing it through it.
pd.read_html()
♪ I get the table, but when trying to print a column, there's a mistake.What am I doing wrong?
Here's the code:
import pandas as pd
url = r'https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%B3%D0%BE%D1%80%D0%BE%D0%B4%D0%BE%D0%B2_%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8'
tables = pd.read_html(url)
cities = tables[0].rename(columns={'Город': 'city'})cities.head()
print(cities['city'])
The mistake's very long, it didn't completely attach it, but the point is, it's a long one.
KeyError: 'city'
♪
-
There's a two-tier multi-indicx, you need to be treated like:
cities[('Города Российской Федерации','city')]
You could just check it out.
cities.columns
:MultiIndex([('Города Российской Федерации', '№'), ('Города Российской Федерации', 'Герб'), ('Города Российской Федерации', 'city'), ('Города Российской Федерации', 'Регион'), ('Города Российской Федерации', 'Федеральный округ'), ('Города Российской Федерации', 'Население'), ('Города Российской Федерации', 'Основание илипервое упоминание'), ('Города Российской Федерации', 'Статус города[5]'), ('Города Российской Федерации', 'Прежние названия')], )