我有一个包含以下变量的数据集。
df.iloc[:, [8, 10,12,14,16]]
m1 m2 m3 m4 m5
0 1.465425 0.369512 0.195093 0.090899 0.075437
1 1.090584 0.630911 0.289951 0.169461 0.065148
2 8.393636 1.147147 0.406641 0.388952 0.284973
3 1.089455 0.265552 0.124755 0.074697 0.066011
4 0.809997 0.465886 0.187011 0.114472 0.049296
5 6.213920 0.820291 0.241337 0.178089 0.169355
6 0.854443 0.327344 0.180940 0.081440 0.066603
7 0.640819 0.581226 0.181652 0.162496 0.072640
8 4.916334 1.024343 0.556189 0.310475 0.301980
9 1.481441 0.318333 0.190325 0.101531 0.070593
10 1.103429 0.569323 0.196212 0.174342 0.097093
我正在尝试通过以下代码叠加直方图:
plotname=["m1", "m2","m3","m4","m5"]
count=0
for var in df.iloc[:, [8,10,12,14,16]]:
print(var, count)
var.hist(var, label=plotname[count])
count=count+1
它失败,并显示以下错误消息:
m1 0
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-67-5a27316eb0a9> in <module>()
3 for var in df.iloc[:, [8,10,12,14,16]]:
4 print(var, count)
----> 5 var.hist(var, label=plotname[count])
6 count=count+1
AttributeError: 'str' object has no attribute 'hist'
一个人如何在熊猫数据框的列上进行for循环并通过类似的代码样式进行绘制?
谢谢,
最佳答案
您可以通过以下方式进行操作:
plotname=["m1","m2","m3","m4","m5"]
for index, var in enumerate(df.iloc[:, [8,10,12,14,16]]):
print(var, index)
df[var].hist(df[var], label=plotname[index])
plt.show()
关于python - AttributeError:'str'对象没有属性'hist',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52660136/