![](/img/trans.png)
[英]Equivalent 'spread' and 'gather' in R/tidyverse in python/pandas?
[英]How do I translate tidyverse from R into pandas from Python?
我正在對 R 和 Python 進行數據分析,以比較它們的差異。 目前我正在努力翻譯
data %>%
mutate(pct_leader = ballotsLeader/validBallots) %>%
group_by(community) %>%
mutate(mean_pct_leader = mean(pct_leader),
sd_pct_leader = sd(pct_leader),
up_pct_leader = mean_pct_leader+2*sd_pct_leader) %>%
filter(pct_leader > up_pct_leader) %>%
top_n(5, pct_leader)
進入 Python。
我嘗試了以下 python 代碼
grouped = data.assign(pct_leader = lambda x: x['ballotsLeader']/x['validBallots']).groupby('community').assign(mean_pct_leader = lambda x: mean(x['pct_leader']),
sd_pct_leader = lambda x: stdev(x['pct_leader']),
up_pct_leader = lambda x: x['mean_pct_leader']+2*x['sd_pct_leader']).query('pct_leader > up_pct_leader').pct_leader.nlargest(5)
但得到一個AttributeError: 'DataFrameGroupBy' object has no attribute 'assign'
錯誤。
我意識到這是因為 DataFrameGroupBy object 沒有分配方法。
如何保留 R 代碼的順序但將其轉換為 python?
編輯:這是我正在使用的數據
| community | province | municipality | precinct | registeredVoters | emptyBallots | invalidBallots | validBallots | ballotsLeader |
|-----------|-----------|--------------|----------|------------------|--------------|----------------|--------------|---------------|
| GALICIA | Coruña, A | Ames | 001 B | 270 | 3 | 7 | 206 | 129 |
| GALICIA | Coruña, A | Ames | 004 A | 356 | 2 | 7 | 257 | 136 |
| GALICIA | Coruña, A | Ames | 002 C | 296 | 1 | 2 | 214 | 149 |
| GALICIA | Coruña, A | Ames | 010 U | 646 | 15 | 10 | 507 | 189 |
| GALICIA | Coruña, A | Ames | 012 B | 695 | 6 | 8 | 479 | 247 |
如果沒有看到一些數據,很難做到這一點,但這應該有效:
(data.assign(pct_leader=data['ballotsLeader'] / data['validBallots'])
.groupby('community').agg(
mean_pct_leader=('pct_leader', 'mean')
sd_pct_leader=('pct_leader', 'std'),
up_pct_leader=('pct_leader', lambda x: (x['pct_leader'].mean()+2) * x['pct_leader'].std())
)
.query('pct_leader > up_pct_leader')
.nlargest(5, 'pct_leader')
)
使用datar
,您可以輕松地將 R 代碼轉換為 python:
from datar.all import f, mutate, group_by, mean, sd, filter, slice_max
data >> \
mutate(pct_leader = f.ballotsLeader/f.validBallots) >> \
group_by(f.community) >> \
mutate(mean_pct_leader = mean(f.pct_leader),
sd_pct_leader = sd(f.pct_leader),
up_pct_leader = f.mean_pct_leader+2*f.sd_pct_leader) >> \
filter(f.pct_leader > f.up_pct_leader) >> \
slice_max(f.pct_leader, n=5)
# top_n() has been superseded in favour of slice_min()/slice_max()
我是 package 的作者。 如果您有任何問題,請隨時提交問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.