python pandas print element of dataframe
16,745
Solution 1
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'
Solution 2
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"]
Author by
Barry Andersen
Updated on June 04, 2022Comments
-
Barry Andersen almost 2 years
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?
-
Barry Andersen over 10 yearsin other words, I should say country = country_codes[country_codes['FIPS']==fips]'COUNTRY'].iloc[0] >>> print(country) Russia right?
-
Andy Hayden over 10 yearsNote: this assumes that country codes are unique (though probably a safe assumption).
-
Weston over 10 yearsThis 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']