簡體   English   中英

在大熊貓中有效地對數據框進行分組?

[英]grouping dataframes in pandas efficiently?

我在熊貓中有以下數據框,其中每一行都有一個唯一的索引( employee ),並且還有一個組標簽type

df = pandas.DataFrame({"employee": ["a", "b", "c", "d"], "type": ["X", "Y", "Y", "Y"], "value": [10,20,30,40]})
df = df.set_index("employee")

我想按type對員工進行分組,然后為每種類型計算一個統計信息。 如何執行此操作,並獲得最終的數據框,該數據框是type x statistic ,例如type x (mean of types) 我嘗試使用groupby

g = df.groupby(lambda x: df.ix[x]["type"])
result = g.mean()

這是低效的,因為它為每行引用df的索引ix是否有更好的方法?

就像@sza所說,您可以使用:

In [11]: g = df.groupby("type")

In [12]: g.mean()
Out[12]:
      value
type
X        10
Y        30

有關更多信息,請參閱groupby文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM