我有一个数据帧,其中包含分类变量和每行的几个属性:

df = ID  C1  C2  .... Cn   flag
      1  a   b         c   True
      1  a   c         d   False
      1  q   t         p   False
      1  g   y         p   False
      2  r   h         k   False

对于每一列和每个ID值,我需要最常见的(和出现的次数)和最后一个值. 我还想知道它的列标志中是否至少有一个‘True’. 所以我会得到:

out = ID c1_common c1_common_n c1_latest c2_common c2_common_n c2_latest ...  has_flag 
       1    a          2             g         y        1           y          True
       2    r          1             r         h        1           h          False

这样做的最佳方式是什么?

推荐答案

正如您前面的问题所述,您必须在计算发生次数之前将数据帧扁平化.最后,GROUP BY ID和CX,然后聚合一些变量:

out = (df.melt('ID').value_counts()
         .rename('count').reset_index('value')
         .groupby(level=['ID', 'variable'])
         .agg(common=('value', 'first'),
              common_n=('count', 'first'),
              latest=('value', 'last'))
         .unstack('variable').swaplevel(axis=1).sort_index(axis=1))

out.columns = out.columns.to_flat_index().str.join('_')

输出:

>>> out

   C1_common  C1_common_n C1_latest C2_common  C2_common_n C2_latest Cn_common  Cn_common_n Cn_latest
ID                                                                                                   
1          a            2         q         b            1         y         p            2         d
2          r            1         r         h            1         h         k            1         k

Python-3.x相关问答推荐

Django 模型类方法使用错误的 `self`

在REPLACE INTO中引用变量会抛出sqlite3.OperationalError

调用 Clear 时 Airflow 会加载新代码吗

如何键入提示函数,在 Python 中通过类decorator 添加到类中

asyncio.as_completed() 应该接受 `Iterable`,但如果输入是 `Generator` 就会崩溃?

如何在 20 秒后重复使用 Pillow 在现有图像上创建新图像?

使用gekko python的混合整数非线性规划

Pandas:从 Pandas 数据框中的 1 和 0 模式中获取值和 ID 的计数

pip install mysqlclient 失败为 mysqlclient 运行 setup.py bdist_wheel ... 错误

smtplib 在 Python 3.1 中发送带有 unicode 字符的邮件的问题

日志(log)模块不适用于 Python3

numpy.ndarray 与 pandas.DataFrame

TensorFlow:dataset.train.next_batch 是如何定义的?

迭代dict值

在计算之前删除包含某些值的组合

Python的max函数有多高效

Python:&= 运算符

如何为 anaconda python3 安装 gi 模块?

哪个更有效:Python 文档字符串还是类型提示?

如何使用异步 for 循环遍历列表?