can*_*his 5 python r pandas dplyr
Python中的Pandas和R中的Dplyr都是灵活的数据整理工具。例如,在R中,使用dplyr可以执行以下操作;
custom_func <- function(col1, col2) length(col1) + length(col2)
ChickWeight %>%
group_by(Diet) %>%
summarise(m_weight = mean(weight),
var_time = var(Time),
covar = cov(weight, Time),
odd_stat = custom_func(weight, Time))
Run Code Online (Sandbox Code Playgroud)
注意如何在一个语句中;
熊猫也有这种可能吗?请注意,我有兴趣在简短的声明中执行此操作(因此,请不要创建三个不同的数据框,然后再将它们加入)。
编辑我注意到这个问题被否决了。如果有人可以提及为什么该职位被否决了,我可能有机会改进这个问题。
使用 pandas groupby.apply(),您可以在 groupby 聚合中运行多个函数。请注意您需要scipy安装统计功能。对于自定义函数,需要像sum()分组数据一样运行聚合:
def customfct(x,y):
data = x / y
return data.mean()
def f(row):
row['m_weight'] = row['weight'].mean()
row['var_time'] = row['Time'].var()
row['cov'] = row['weight'].cov(row['Time'])
row['odd_stat'] = customfct(row['weight'], row['Time'])
return row
aggdf = df.groupby('Diet').apply(f)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1463 次 |
| 最近记录: |