2016-12-05 41 views
-2

最初にディメンション "Customer"で集計した変数( "PurchAmount")に集計関数(sum())を適用したいと思います。同時に、私は列 "Quantity"を選択したいと思います。 RでPandas DataFrameでのグループ化/集計と同時に選択

これがで可能です:

myData[, list(Quantity, AggPurch=sum(PurchAmount)), by=Customer] 

はPythonでパンダDATAFRAMEのための同様の解決策はありますか?

+0

@Rich Scriven私の唯一の編集では、偽のR taこの質問についてはg。編集を通してでない場合、どのように達成すべきでしょうか? – G5W

答えて

0

あなたは '.groupby' を使用してグループにパンダを分割することができます:

http://pandas.pydata.org/pandas-docs/stable/groupby.html#splitting-an-object-into-groups

import pandas as pd 

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 
    'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 
    'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 
    'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3], 
    'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]} 

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore']) 

df['preTestScore'].groupby([df['regiment'], df['company']]).mean() 

DFのための出力は次のようになります。

regiment company 
Dragoons 1st   3.5 
      2nd  27.5 
Nighthawks 1st  14.0 
      2nd  16.5 
Scouts  1st   2.5 
      2nd   2.5 
dtype: float64 

例から: http://chrisalbon.com/python/pandas_apply_operations_to_groups.html

関連する問題