pandas python pandas打印数据框的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20766278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python pandas print element of dataframe
提问by Barry Andersen
I have a pandas data frame named country_codes:
我有一个名为 country_codes 的 Pandas 数据框:
>>> 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 代码:
>>> fips = 'RS'
I select the country name corresponding to that fips code:
我选择与该 fips 代码对应的国家/地区名称:
>>> 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?
我想在 matplotlib 绘图的标题中使用该国家/地区名称。我只想要国名。我不想要索引号或显示 Name: COUNTRY, dtype: object 的行。我怎么只得到名字?
回答by Weston
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'
回答by HYRY
I think create a series with FIPS as the key and COUNTRY as the value will make the code simpler:
我认为创建一个以 FIPS 为键和 COUNTRY 为值的系列将使代码更简单:
fips = pd.Series(df["COUNTRY"].values, index=df["FIPS"])
then you can get the country by:
那么你可以通过以下方式获得国家:
fips["AL"]

