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))
注意如何在一条语句中;
- 我可以在一行中聚合多个列。
- 我可以在一行中对这些多列应用不同的函数。
- 我可以使用考虑两列的函数。
- 我可以为其中任何一个添加自定义函数。
- 我可以为这些聚合声明新的列名。
pandas 中也可以使用这种模式吗?请注意,我有兴趣在简短的声明中执行此操作(因此不要创建三个不同的数据框然后加入它们)。
最佳答案
与 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)
关于python - Pandas :聚合具有多种功能的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938393/