Group by分组主要涉及到下面三个操作:
- 分组 按需求将数据分成若干组
- 运算 对每个分组进行单独的运算
- 合并 对运算的结果进行合并
分组模式及其对象
learn_pandas
数据集
df = pd.read_csv('data/learn_pandas.csv')
df <- read.csv('data/learn_pandas.csv', stringsAsFactors = FALSE)
分组的一般模式
# Python
df.groupby('Gender')['Height'].mean()
# R
df %>%
group_by(Gender) %>%
summarise(Height = mean(Height, na.rm = TRUE))
# SQL
select Gender
,avg(Height) as Height_avg
from learn_pandas
group by Gender
分组依据的本质
# Python
df.groupby(['School', 'Gender'])['Height'].mean()
# R
df %>%
group_by(School, Gender) %>%
summarise(Height = mean(Height, na.rm = TRUE))
# Python
df.Weight.mean()
condition = df.Weight > df.Weight.mean()
df.groupby(condition)['Height'].mean()
df.groupby(df.Weight > df.Weight.mean())['Height'].mean()
# R
mean(df$Weight, na.rm = TRUE)
condition <- df$Weight > mean(df$Weight, na.rm = TRUE)
df %>%
group_by(Weight = Weight > mean(Weight, na.rm = TRUE)) %>%
summarise(Height = mean(Height, na.rm = TRUE), n())
# Python
item = np.random.choice(list('abc'), df.shape[0])
df.groupby(item)['Height'].mean()
df.groupby([condition, item])['Height'].mean()
# R
item <- py$item
df %>%
group_by(item = item) %>%
summarise(Height = mean(Height, na.rm = TRUE))
df %>%
group_by(condition, item = item) %>%
summarise(Height = mean(Height, na.rm = TRUE))
# Python
df[['School', 'Gender']].drop_duplicates()
df.groupby([df['School'], df['Gender']])['Height'].mean()
# R
df %>%
distinct(School, Gender)
df %>%
group_by(School, Gender)