gpt4 book ai didi

python - 广播 groupby 结果作为原始 DataFrame 中的新列

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:53 28 4
gpt4 key购买 nike

我正在尝试基于分组数据框中的两列在 Pandas 数据框中创建一个新列。

具体来说,我正在尝试复制此 R 代码的输出:

library(data.table)

df = data.table(a = 1:6,
b = 7:12,
c = c('q', 'q', 'q', 'q', 'w', 'w')
)


df[, ab_weighted := sum(a)/sum(b), by = "c"]
df[, c('c', 'a', 'b', 'ab_weighted')]

输出:

enter image description here

到目前为止,我在 Python 中尝试了以下操作:

import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[7,8,9,10,11,12],
'c':['q', 'q', 'q', 'q', 'w', 'w']
})

df.groupby(['c'])['a', 'b'].apply(lambda x: sum(x['a'])/sum(x['b']))

输出:

enter image description here

当我将上面代码中的 apply 更改为 transform 时,出现错误:类型错误:需要一个整数

转换工作正常,但如果我只使用一个列:

import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[7,8,9,10,11,12],
'c':['q', 'q', 'q', 'q', 'w', 'w']
})

df.groupby(['c'])['a', 'b'].transform(lambda x: sum(x))

但显然,这不是同一个答案:

enter image description here

有没有一种方法可以从 Pandas 中的 data.table 代码中获取结果而不必生成中间列(因为这样我就可以在最后一列上使用 transform

非常感谢任何帮助:)

最佳答案

只需使用 map 修复您的代码,Rpandas 仍然有不同的 ,这意味着不是每个 R您可以在 pandas

中找到替代函数
df.c.map(df.groupby(['c'])['a', 'b'].apply(lambda x: sum(x['a'])/sum(x['b'])))
Out[67]:
0 0.294118
1 0.294118
2 0.294118
3 0.294118
4 0.478261
5 0.478261
Name: c, dtype: float64

关于python - 广播 groupby 结果作为原始 DataFrame 中的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747080/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com