Inside Introduction to Pandas:
11. Selecting Items from a Series by Label
countries = f500[‘country’]
countries_counts = countries.value_counts()
india_company = countries[“India”]
india = countries_counts[‘India’]
I am getting error when trying to execute :
india_company = countries[“India”]
Error:
{{{{{andas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: ‘India’}}}}}
But the line below executed properly.
india = countries_counts[‘India’]
Both countries, and countries_counts are Series
Hi @charulagarwal ,
Welcome to the Community!
Both countries_counts
and countries
are Series objects. The difference is that in countries_counts
“India” is an index, while in countries
it’s a value (actually, there are several values “India” there, since there are several companies). Hence the syntax for extracting the data for India will be different for both series.
If you want to extract all the Indian companies from countries
, you can use the following piece of code:
countries.loc[countries == 'India'].index.tolist()
This part countries.loc[countries == 'India']
extracts from countries
all the rows for India, as a new Series object.
The index
selects only the index of this new Series object (i.e., the names of the Indian companies).
tolist()
renders the index object (which was pandas.core.indexes.base.Index
) into a list.
For your future technical questions in the Community, you can find helpful these guidelines:
We want to help our learners make progress towards their goals as fast as possible. That is why we are introducing 5 guidelines for all technical questions asked in our Community.
This might seem counterintuitive to some.
“I need to ask my question, now! Following some guidelines will only slow me down.”
Trust me, it won’t. These guidelines will ensure that you get your answers faster. Here’s how:
Guidelines will allow volunteers and Learning Assistants to understand your questions more eas…