python - 计算 Pandas 中分组数据的权重

标签 python pandas

我想用 pandas 数据框计算投资组合权重。以下是一些虚拟数据的示例:

df1 = DataFrame({'name' : ['ann','bob']*3}).sort('name').reset_index(drop=True)
df2 = DataFrame({'stock' : list('ABC')*2})
df3 = DataFrame({'val': np.random.randint(10,100,6)})
df = pd.concat([df1, df2, df3], axis=1)

enter image description here

每个人拥有 3 支股票,其值(value)为 val。我们可以这样计算投资组合权重:

df.groupby('name').apply(lambda x: x.val/(x.val).sum())

这给出了这个:

enter image description here

如果我想将列 wgt 添加到 df,我需要将此结果合并回 df on name索引。这看起来相当笨拙。

有没有办法一步到位?或者最好利用 pandas 特性的方法是什么?

最佳答案

使用transform,这将返回一个索引与原始 df 对齐的系列:

In [114]:
df['wgt'] = df.groupby('name')['val'].transform(lambda x: x/x.sum())
df

Out[114]:
  name stock  val       wgt
0  ann     A   18  0.131387
1  ann     B   43  0.313869
2  ann     C   76  0.554745
3  bob     A   16  0.142857
4  bob     B   44  0.392857
5  bob     C   52  0.464286

关于python - 计算 Pandas 中分组数据的权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31811457/

相关文章:

Python 将逗号分隔的数字解析为 int

python - psycopg2 : Insert a numpy array of strings into an PostgreSQL table

python - 对 pandas df 中的前 N ​​组和组 'others' 进行排序

python - 导入 pandas 时脚本挂起

python - 我可以让 mean_iou 依赖于 update_op 吗?它们都由 tf.metrics.mean_iou() 返回

Python:为什么调用 '__init__' 而不是 className()?

python - 更改由列表组成的 df 列

python - pd.notnull 奇怪的 null 检查行为

python - 在同一 df 中的 df col 行中仅选择一个值,以获取不同 val 的计算结果,并且一次仅对一个股票代码进行计算 df

Python eval 字符串中的整数,并返回整数而不是 ascii 字符