python – 计算由长度不等的索引的二维列表给出的DataFrame行组的平均值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 计算由长度不等的索引的二维列表给出的DataFrame行组的平均值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3279字,纯文字阅读大概需要5分钟。
内容图文
![python – 计算由长度不等的索引的二维列表给出的DataFrame行组的平均值](/upload/InfoBanner/zyjiaocheng/789/2d20553fe6a14b7b832cdea205cc575a.jpg)
我有一个有n行的DataFrame.我还有一个二维索引数组.该数组也有n行,但每行的长度可以变化.我需要根据索引对DataFrame行进行分组并计算列的平均值.
例如:
如果我有DataFrame df和array ind,我需要得到
[df.loc [ind [n],col_name] .mean()for n in ind].
我已经使用apply pandas函数实现了这个:
size = 100000
df = pd.DataFrame(columns=['a'])
df['a'] = np.arange(size)
np.random.seed(1)
ind = np.array([np.random.randint(0, size, size=5) for _ in range(size)])
def group(row):
return df.loc[ind[df.index.get_loc(row.name)], 'a'].mean()
df['avg'] = df.apply(group, axis=1)
但这很慢并且规模很小.在这种情况下,它的速度要快得多
df.a.values[ind].mean(axis=1)
但是,据我所知,这只是因为ind的所有元素都是相同的长度,并且以下代码不起作用:
new_ind = ind.tolist()
new_ind[0].pop()
df.a.values[new_ind].mean(axis=1)
我玩弄了大熊猫的方法,但没有成功.是否有另一种有效的方法根据长度不等的索引列表对行进行分组并返回列的平均值?
解决方法:
建立
为了演示目的,保持数据帧更短
np.random.seed(1)
size = 10
df = pd.DataFrame(dict(a=np.arange(size)))
# array of variable length sub-arrays
ind = np.array([
np.random.randint(
0, size, size=np.random.randint(1, 11)
) for _ in range(size)
])
解
将np.bincount与weights参数一起使用.
这应该是一个非常快速的解决方案.
# get an array of the lengths of sub-arrays
lengths = np.array([len(x) for x in ind])
# simple np.arange for initial positions
positions = np.arange(len(ind))
# get at the underlying values of column `'a'`
values = df.a.values
# for each position repeated the number of times equal to
# the length of the sub-array at that position,
# add to the bin, identified by the position, the amount
# from values at the indices from the sub-array
# divide sums by lengths to get averages
avg = np.bincount(
positions.repeat(lengths),
values[np.concatenate(ind)]
) / lengths
df.assign(avg=avg)
a avg
0 0 3.833333
1 1 4.250000
2 2 6.200000
3 3 6.000000
4 4 5.200000
5 5 5.400000
6 6 2.000000
7 7 3.750000
8 8 6.500000
9 9 6.200000
定时
此表标识每行的最小时间量,该行中的每个其他值表示为最小值所用时间的倍数.最后一列标识了相应行指定的数据长度的最快方法.
Method pir mcf Best
Size
10 1 12.3746 pir
30 1 44.0495 pir
100 1 124.054 pir
300 1 270.6 pir
1000 1 576.505 pir
3000 1 819.034 pir
10000 1 990.847 pir
码
def mcf(d, i):
g = lambda r: d.loc[i[d.index.get_loc(r.name)], 'a'].mean()
return d.assign(avg=d.apply(g, 1))
def pir(d, i):
lengths = np.array([len(x) for x in i])
positions = np.arange(len(i))
values = d.a.values
avg = np.bincount(
positions.repeat(lengths),
values[np.concatenate(i)]
) / lengths
return d.assign(avg=avg)
results = pd.DataFrame(
index=pd.Index([10, 30, 100, 300, 1000, 3000, 10000], name='Size'),
columns=pd.Index(['pir', 'mcf'], name='Method')
)
for i in results.index:
df = pd.DataFrame(dict(a=np.arange(i)))
ind = np.array([
np.random.randint(
0, i, size=np.random.randint(1, 11)
) for _ in range(i)
])
for j in results.columns:
stmt = '{}(df, ind)'.format(j)
setp = 'from __main__ import df, ind, {}'.format(j)
results.set_value(i, j, timeit(stmt, setp, number=10))
results.div(results.min(1), 0).round(2).pipe(lambda d: d.assign(Best=d.idxmin(1)))
fig, (a1, a2) = plt.subplots(2, 1, figsize=(6, 6))
results.plot(loglog=True, lw=3, ax=a1)
results.div(results.min(1), 0).round(2).plot.bar(logy=True, ax=a2)
内容总结
以上是互联网集市为您收集整理的python – 计算由长度不等的索引的二维列表给出的DataFrame行组的平均值全部内容,希望文章能够帮你解决python – 计算由长度不等的索引的二维列表给出的DataFrame行组的平均值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。