Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Pandas DataFrame groupby() 方法

❮ DataFrame 参考


示例

查找每个汽车品牌的平均二氧化碳排放量

import pandas as pd

data = {
  'co2': [95, 90, 99, 104, 105, 94, 99, 104],
  'model': ['Citigo', 'Fabia', 'Fiesta', 'Rapid', 'Focus', 'Mondeo', 'Octavia', 'B-Max'],
  'car': ['Skoda', 'Skoda', 'Ford', 'Skoda', 'Ford', 'Ford', 'Skoda', 'Ford']
}

df = pd.DataFrame(data)

print(df.groupby(["car"]).mean())
自己尝试 »

定义和用法

The groupby() 方法允许你对数据进行分组并在这些组上执行函数。


语法

dataframe.transform(by, axis, level, as_index, sort, group_keys, observed, dropna)

参数

axislevelas_indexsortgroup_keysobserveddropna 参数是关键字参数

参数 描述
by   必填。标签、标签列表或用于指定如何对 DataFrame 进行分组的函数。
axis 0
1
'index'
'columns'
可选,对哪个轴进行分组,默认为 0。
level level
None
可选。指定是否应按特定级别进行分组。默认为 None
as_index True
False
可选,默认为 True。如果结果不应使用组标签作为索引,则设置为 False
sort True
False
可选,默认为 True。如果结果不应排序组键(以获得更好的性能),则设置为 False
group_keys True
False
可选,默认为 True。如果结果不应将组键添加到索引,则设置为 False
dropna True
False
可选,默认为 True。如果结果应包含组键为 NULL 值的行/列,则设置为 False

返回值

一个 DataFrameGroupBy 对象,其中行/列已分组。


❮ DataFrame 参考

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.