1、groupby 与 apply的结合使用

  • groupby:主要用于分组聚合,可结合统计函数(mean()、min()、sum()、count()、、、)一起使用,跟聚合函数agg()类 似;
  • apply:可以利用函数包括自定义函数迭代计算,可以结合lambda使用
1)对dataframe进行分组,并将分组结果合并(某列多行变一行)
df = pd.DataFrame(data=[[1,2,'book1'], [1, 2, 'book2'], [4, 5, 'book3']], columns=['ID', 'Day', 'title'])
print(df)
df.groupby(['ID', 'Day'])['title'].apply(list)

python dataframe 的高级操作

2) 对dataframe进行分组,并将分组结果合并后排序或将list转tuple,以及将某一值映射(贴标签)
test = pd.DataFrame(data=[['1',['物理', '历史', '数学']], ['2', ['历史', '物理', '数学']], ['3', ['历史', '语文', '数学']]], columns=['id', 'subject'])
print(test)

test['subject'].apply(lambda str : str.sort(), str)
print(test)

#test['km'] = test['km'].apply(lambda str : tuple(str))
test['subject_str'] = test['subject'].apply(lambda str : str[0] + '_' + str[1] + '_' + str[2])
print(test)

mapping = {'历史_语文_数学': 'a', '历史_数学_物理':'b', '历史_数学_语文': 'c'}
test['label'] = test['subject_str'].replace(mapping)
print(test)

python dataframe 的高级操作

相关文章:

  • 2022-01-06
  • 2021-07-21
  • 2022-12-23
  • 2021-05-18
  • 2021-08-10
  • 2021-11-18
  • 2021-09-21
  • 2021-05-21
猜你喜欢
  • 2022-12-23
  • 2021-12-30
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案