2

I have a pandas data frame named country_codes:

>>> country_codes.head(3)

       COUNTRY FIPS ISO2 ISO3

0  Afghanistan   AF   AF  AFG

1      Albania   AL   AL  ALB

2      Algeria   AG   DZ  DZA

given a particular fips code:

>>> fips = 'RS'

I select the country name corresponding to that fips code:

>>> country = country_codes[country_codes['FIPS']==fips]['COUNTRY']

and print it:

>>> print(country)

201    Russia

Name: COUNTRY, dtype: object

I want to use that country name in the title of a matplotlib plot. I want the country name only. I do not want the index number or the line that says Name: COUNTRY, dtype: object. How do I get the name only?

3 Answers 3

4

You're getting a series from indexing the dataframe

>>> country = country_codes[country_codes['FIPS']==fips]['COUNTRY']
>>> type(country)
<class 'pandas.core.series.Series'>

For a Series, selection by position:

>>> country.iloc[0]
'Russia'
Sign up to request clarification or add additional context in comments.

1 Comment

in other words, I should say country = country_codes[country_codes['FIPS']==fips]'COUNTRY'].iloc[0] >>> print(country) Russia right?
1

I think create a series with FIPS as the key and COUNTRY as the value will make the code simpler:

fips = pd.Series(df["COUNTRY"].values, index=df["FIPS"])

then you can get the country by:

fips["AL"]

2 Comments

Note: this assumes that country codes are unique (though probably a safe assumption).
This is the way to do it. It is dramatically faster code than navigating the dataframe. One alternate approach to getting the 'COUNTRY' Series indexed by 'FIPS' would be df.set_index('FIPS')['COUNTRY']
0

if you have pandas data series , and how to access via index is as below

import numpy as np
import pandas as pd 
data=np.array([176.2,158.4,167.6,156.2,161.4])
heights=pd.Series(data,index=['s1','s2','s3','s4','s5'])
print(heights['s2'])

Comments

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.