2016-06-01 10 views
1

私はpandas groupbyを使用しており、グループ内のアイテムからセットを作成する機能を適用したいと考えています。Pandas groupbyとアイテムセットを作成

次は動作しません:

df = df.groupby('col1')['col2'].agg({'size': len, 'set': set}) 

しかし、次の作品:私の理解で

def to_set(x): 
    return set(x) 

df = df.groupby('col1')['col2'].agg({'size': len, 'set': to_set}) 

2つの発現は、最初は動作しない理由は何であるか、似ていますか?

答えて

3

to_settypefunctionであるのに対し、settypetypeであるためにです:

type(set) 
<class 'type'> 

def to_set(x): 
    return set(x) 

type(to_set) 

<class 'function'> 

docsによると、.agg()を期待:完全性については

arg : function or dict

Function to use for aggregating groups.

  • If a function , must either work when passed a DataFrame or when passed to DataFrame.apply .

  • If passed a dict , the keys must be DataFrame column names.

Accepted Combinations are:

  • string cythonized function name
  • function

  • list of functions

  • dict of columns -> functions

  • nested dict of names -> dicts of functions

+0

、それは誤り 'TypeError例外を発生させます。 ' 'オブジェクトはiterableではありません'と入力してください。おそらく*関数*を渡さないと関数のリストが必要になるからです。 – ayhan

関連する問題