python – 将字符串的Pandas DataFrame转换为直方图
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 将字符串的Pandas DataFrame转换为直方图,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2175字,纯文字阅读大概需要4分钟。
内容图文
![python – 将字符串的Pandas DataFrame转换为直方图](/upload/InfoBanner/zyjiaocheng/701/157d49c464194a088a72d09fc689f3f3.jpg)
假设我有一个像这样创建的DataFrame:
import pandas as pd
s1 = pd.Series(['a', 'b', 'a', 'c', 'a', 'b'])
s2 = pd.Series(['a', 'f', 'a', 'd', 'a', 'f', 'f'])
d = pd.DataFrame({'s1': s1, 's2', s2})
实际数据中的字符串中存在相当多的稀疏性.我想创建字符串出现的直方图,看起来像d.hist()(例如,带有子图)为s1和s2(每个子图一个)生成的字符串.
只是做d.hist()给出了这个错误:
/Library/Python/2.7/site-packages/pandas/tools/plotting.pyc in hist_frame(data, column, by, grid, xlabelsize, xrot, ylabelsize, yrot, ax, sharex, sharey, **kwds)
1725 ax.xaxis.set_visible(True)
1726 ax.yaxis.set_visible(True)
-> 1727 ax.hist(data[col].dropna().values, **kwds)
1728 ax.set_title(col)
1729 ax.grid(grid)
/Library/Python/2.7/site-packages/matplotlib/axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
8099 # this will automatically overwrite bins,
8100 # so that each histogram uses the same bins
-> 8101 m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
8102 if mlast is None:
8103 mlast = np.zeros(len(bins)-1, m.dtype)
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/function_base.pyc in histogram(a, bins, range, normed, weights, density)
167 else:
168 range = (a.min(), a.max())
--> 169 mn, mx = [mi+0.0 for mi in range]
170 if mn == mx:
171 mn -= 0.5
TypeError: cannot concatenate 'str' and 'float' objects
我想我可以手动浏览每个系列,执行value_counts(),然后将其绘制为条形图,并手动创建子图.我想检查是否有更简单的方法.
解决方法:
重新创建数据框:
import pandas as pd
s1 = pd.Series(['a', 'b', 'a', 'c', 'a', 'b'])
s2 = pd.Series(['a', 'f', 'a', 'd', 'a', 'f', 'f'])
d = pd.DataFrame({'s1': s1, 's2': s2})
要根据需要获得带有子图的直方图:
d.apply(pd.value_counts).plot(kind='bar', subplots=True)
OP在问题中提到了pd.value_counts.我认为缺少的部分只是没有理由“手动”创建所需的条形图.
d.apply(pd.value_counts)的输出是一个pandas数据帧.我们可以像任何其他数据框一样绘制值,并选择subplots = True选项为我们提供了我们想要的.
内容总结
以上是互联网集市为您收集整理的python – 将字符串的Pandas DataFrame转换为直方图全部内容,希望文章能够帮你解决python – 将字符串的Pandas DataFrame转换为直方图所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。