我有不同国家的生育率数据,我想:
一。重命名列
2。仅打印特定国家(不使用索引,而使用名称)
这里我从网站导入数据
df = pd.read_html('https://www.cia.gov/library/publications/the-world-factbook/fields/2127.html')
然后尝试重命名列(从“0”重命名为“Country”,从“1”重命名为“TFR”):
df= df.rename(index=str, columns ={'0':'Country', '1':'TFR'})
但我收到错误信息:
df = df.rename(index=str, columns ={'0':'Country', '1':'TFR'})
AttributeError: 'list' object has no attribute 'rename'
这是我试图寻找特定国家的方式:
print(df[df['0'].str.contains("Tanzan")])
我得到以下错误:
TypeError: list indices must be integers or slices, not str
我做错什么了?如何解决(如果可能的话)?谢谢你的帮助!
最佳答案
首先添加参数header=0
用于将页的第一行转换为数据帧的标题,然后添加[0]
用于从数据帧列表中选择第一个数据帧:
url = 'https://www.cia.gov/library/publications/the-world-factbook/fields/2127.html'
d = {'TOTAL FERTILITY RATE(CHILDREN BORN/WOMAN)':'TFR'}
df = pd.read_html(url, header=0)[0].rename(columns=d)
print (df.head())
Country TFR
0 Afghanistan 5.12 children born/woman (2017 est.)
1 Albania 1.51 children born/woman (2017 est.)
2 Algeria 2.7 children born/woman (2017 est.)
3 American Samoa 2.68 children born/woman (2017 est.)
4 Andorra 1.4 children born/woman (2017 est.)
按新列名筛选的最后一个:
print(df[df['Country'].str.contains("Tanzan")])
Country TFR
204 Tanzania 4.77 children born/woman (2017 est.)
关于python - 如何从数据框( Pandas )中打印特定值(字符串)的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52737951/