绘制每个 pandas 的唯一值计数的键计数
it1352
帮助1人
问题说明
我有一组数据,我希望根据这些数据绘制每个唯一ID计数的键数(em = x),并且我我试图学习如何利用pandas
.
I have a set of data from which I want to plot the number of keys per unique id count (x=unique_id_count, y=key_count), and I'm trying to learn how to take advantage of pandas
.
在这种情况下:
unique_ids 1 =密钥计数2
unique_ids 1 = key count 2
unique_ids 2 =密钥计数1
unique_ids 2 = key count 1
from pandas import *
key_items = ("a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c")
id_data = ("X", "X", "X", "X", "X", "X", "X", "Y", "Y", "Y", "X", "X", "X")
df = DataFrame({'keys': key_items, 'ids': id_data})
我设法通过从数据框中提取数据并对其进行重组,然后重新构建一个新的数据框来将数据整理到所需的位置.在这种情况下,最好在不带熊猫的python中完成所有操作……
I've managed to mangle the data into what I want by pulling out the data from the dataframe and restructuring it, and rebuilding a new dataframe. In this case it's probably better to do it all in python without pandas...
unique_values = defaultdict(list)
for items in df.itertuples(index=False):
key = items[1]
v = items[0]
unique_values[key].append(v)
unique_values_count = {}
for k, values in unique_values.iteritems():
unique_values_count[k] = [len(set(values))]
# reformat for plotting
key_col = ("a", "b", "c")
id_col = [unique_values_count[k][0] for k in key_col]
df2 = DataFrame({"keys":key_col, "unique_id_count": id_col})
df2.groupby("unique_id_count").size().plot(kind="bar")
有没有更好的方法可以使用初始数据帧更直接地做到这一点?
Is there a better way to do this more directly using the initial dataframe?
正确答案
#1
s = df.groupby("keys").ids.agg(lambda x:len(x.unique()))
pd.value_counts(s).plot(kind="bar")
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgkeij
系列文章
更多
同类精品
更多
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20