我正在DataQuest中做一个练习,试图绘制从SQL中获得的一组数据。
它给了我错误:
AttributeError:'str'对象没有属性'values'
如何在x轴上显示name
,在y轴上显示Pop_Density
?我知道Python无法显示名称,但如何将名称和数字一起引用?我是否必须先将DataFrame转换成字典?问题所在的行在下面评论。
import pandas as pd
import sqlite3
conn = sqlite3.connect("factbook.db")
q7 = '''
SELECT name, CAST(population as float)/CAST(area_land as float) AS Pop_Density
FROM facts
ORDER BY Pop_Density DESC
LIMIT 20
'''
density = pd.read_sql_query(q7, conn)
print(density)
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
bar_heights = density['name'].iloc[0].values # <-- line with problem.
bar_positions = arange(5) + 0.75
tick_positions = range(1, 20)
ax.bar(bar_positions, bar_heights, 0.5)
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols, rotation=90)
ax.set_xlabel("Country")
ax.set_ylabel("Population Density")
ax.set_title("Countries With The Highest Population Density")
答案 0 :(得分:2)
bar_heights = density['Pop_Density'].values
bar_positions = np.arange(len(bar_heights)) + 0.75
tick_positions = range(1, len(bar_heights) + 1)
ax.bar(bar_positions, bar_heights, 0.5)
ax.set_xticks(tick_positions)
ax.set_xticklabels(density['name'], rotation=90)