2016-11-06 3 views
0

私はPythonの初心者で、カラムのサブセット(スライス?)でデータフレームのインスタンスを設定しようとしています。両方がうまくいくはずですが、理由を理解しようとする。 ( '名前'、 'コスト') 法1:カラムのサブセットでデータフレームをスライスする

import pandas as pd 
purchase_1 = pd.Series({'Name': 'Chris', 
         'Item Purchased': 'Dog Food', 
         'Cost': 22.50}) 
purchase_2 = pd.Series({'Name': 'Kevyn', 
         'Item Purchased': 'Kitty Litter', 
         'Cost': 2.50}) 
purchase_3 = pd.Series({'Name': 'Vinod', 
         'Item Purchased': 'Bird Seed', 
         'Cost': 5.00}) 

df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2']) 
columns_to_keep = ['Name','Cost'] 
df = df[columns_to_keep] 

方法2:

import pandas as pd 
purchase_1 = pd.Series({'Name': 'Chris', 
         'Item Purchased': 'Dog Food', 
         'Cost': 22.50}) 
purchase_2 = pd.Series({'Name': 'Kevyn', 
         'Item Purchased': 'Kitty Litter', 
         'Cost': 2.50}) 
purchase_3 = pd.Series({'Name': 'Vinod', 
         'Item Purchased': 'Bird Seed', 
         'Cost': 5.00}) 

df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2']) 
columns_to_keep = ['Name','Cost'] 
df = df['Name','Cost'] 

は、私の知る限り見ることができるように、両方が設定されているように見える 方法1作品が、方法2は、エラーKeyError例外を返します。列のリストを持つインスタンスdf method2が機能しない理由を理解したいですか?

答えて

2

これはnumpy/pandasのadvanced index slicingの仕組みです。方法2にdf = df['Name','Cost']df = df[('Name','Cost')]と同じであることを

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool)

注 - 選択オブジェクトとしてタプルを使用して暗示います。基本索引付けと呼ばれます。

In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN] ; the latter is just syntactic sugar for the former.

は、あなたは、外出先で複数の列から項目を選択します高度なインデックス作成をトリガするために(1あなたの方法のように)配列でないタプルリストを列を配置する必要があります。

>>> df = df[['Name','Cost']] # also df[np.array(['Name','Cost'])] works 
>>> df 
      Name Cost 
Store 1 Chris 22.5 
Store 1 Kevyn 2.5 
Store 2 Vinod 5.0 
+0

説明していただきありがとうございます – Rubans

関連する問題