python - 如何将 pandas groupby.apply(f) 的一系列(例如)结果放入数据框的新列中?

标签 python pandas

我有一个数据框,我想计算统计数据(value_count、模式、平均值等),然后将结果放入新列中。我当前的解决方案是 O(n**2) 左右,而且我确信可能有一种我忽略的更快、明显的方法。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(10, size=(100, 10)), 
                   columns = list('abcdefghij'))

df['result'] = 0

groups = df.groupby([df.i, df.j])
for g in groups:
    icol_eq = df.i == g[0][0]
    jcol_eq = df.j == g[0][1]
    i_and_j = icol_eq & jcol_eq
    df['result'][i_and_j] = len(g[1])

上面的方法有效,但对于大型数据帧来说速度非常慢。

我试过了

df['result'] = df.groupby([df.i, df.j]).apply(len)

但似乎不起作用。

也没有

def f(g):
    g['result'] = len(g)
    return g

df.groupby([df.i, df.j]).apply(f)

我也不能合并 df.groupby.apply(lambda x: len(x)) 的结果系列

最佳答案

您想使用transform :

In [98]:

df['result'] = df.groupby([df.i, df.j]).transform(len)
df
Out[98]:
    a  b  c  d  e  f  g  h  i  j  result
0   6  1  3  0  1  1  4  2  8  6       6
1   1  3  9  7  5  5  3  5  4  4       1
2   1  5  0  1  8  1  4  7  3  9       1
3   6  8  6  4  6  0  8  0  6  5       6
4   7  9  7  2  8  9  9  6  0  6       7
5   3  5  5  7  2  7  7  3  2  8       3
6   5  0  4  7  5  7  5  7  9  1       5
7   3  2  5  4  3  6  8  4  2  0       3
8   2  3  0  4  8  5  7  9  7  2       2
9   1  1  3  2  3  5  6  6  5  6       1
10  3  0  2  7  1  8  1  3  5  4       3
....

transform 返回一个系列,其索引与原始 df 对齐,以便您可以将其添加为列

关于python - 如何将 pandas groupby.apply(f) 的一系列(例如)结果放入数据框的新列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246548/

相关文章:

python - Pandas : first datetime field gets automatically converted to timestamp type

python - 如何使用pip下载和安装Python包和模块以及无法通过pip下载的包和模块?

python - 在 python 的 argparse 模块中,如何禁用大括号之间的打印子命令选择?

python - 这些变量是什么?

python - 按日期列值的比例分布

python - pandas 系列及其所有元素的排列 (itertools)

Python:搜索元组列表,删除整个索引

python - 如何获取网页中的特定框架并检索其内容

python - 为什么我的数组值没有更新?线性回归

python - Pandas read_csv : low_memory and dtype options