我有一个数据框,我想计算统计值(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对齐的Series,然后可以将其添加为列
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句