【问题标题】:pandas: How to list total number of users for each group and all users in group?pandas:如何列出每个组的用户总数和组中的所有用户?
【发布时间】:2019-06-12 06:38:57
【问题描述】:

我在 jupyter notebook 中有以下代码:  

import h5py
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_hdf('accounting-2018-10-deid.h5', 'table')
df.columns
Out[4]:
Index(['group', 'owner', 'job_number', 'submission_time', 'start_time',
   'end_time', 'failed', 'exit_status', 'granted_pe', 'slots',
   'task_number', 'maxvmem', 'h_data', 'h_rt', 'highp', 'exclusive',
   'h_vmem', 'gpu', 'pe', 'slot', 'wait_time', 'wtime', 'campus'],
  dtype='object')

各列的含义:

owner: the owner of a job
group: the group a owner belongs to; a group can have one or more owners

任务是: 对于每个组,列出用户数量,并列出所有这些用户(即具有相同“组”字段的用户)。 例如:组 1(4 个用户):user2、user32、user41、user56?

我尝试使用 groupby() 但没有得到正确答案。 请帮我。

【问题讨论】:

标签: python jupyter-notebook pandas-groupby


【解决方案1】:

这对你有用吗?

import pandas as pd

df = pd.DataFrame({"owner": ["Allen", "Bob", "Cindy", "David", "Emily", "Frank"],
                   "group": ["A", "C", "B", "C", "B", "B"]})

groups = df.groupby("group")
for group in groups:
    print('There are {} owners in group {}'.format(group[1].shape[0], group[0]))
    print('They are {}.'.format(group[1].owner.to_string(index=False).replace('\n', ', ')))
    print()

【讨论】:

  • 嗨 keineahnung2345,我按照你的建议做了,但是得到 MemoryError MemoryError Traceback(最近一次调用最后一次) in 1 groups = df.groupby("group ") ----> 2 for group in groups: 3 # print('There are {} owner in group {}'.format(group[1].shape[0], group[0])) 4 print( group[1]) 5 # print('他们是 {}.'.format(group[1].owner.to_string(index=False).replace('\n', ', '))) .... . 内存错误:
  • @TalNur 我猜这是因为您的数据集太大。你能用更小的数据集试试这个方法,看看它是否有效?您也可以尝试在pd.read_hdf() 中添加low_memory=Falseusecols=['group', 'owner'],就像stackoverflow.com/questions/17557074/…stackoverflow.com/questions/26063231/… 建议的那样,看看它们是否有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 2016-07-19
  • 2023-04-06
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
相关资源
最近更新 更多