2017-08-06 10 views
1

DataFrameのインデックス/カラムに見つからない要素を含むリストがいくつかあります。これらのインデックスを使用して特定の行/列を取得して、リストの要素がインデックス/列に見つからない場合は無視されるようにします。インデックス/カラムに見つからない要素を含む可能性のあるリストを.locを使用してDFをスライスする方法

df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5], 
    "y":[3, 4, 5, 6, 7]}, 
    index=['a', 'b', 'c', 'd', 'e']) 

df1.loc[['c', 'd', 'e', 'f'], ['x', 'z']] 

私が取得したい:

 x 
c 3.0 
d 4.0 
e 5.0 

の代わり:

 x z 
c 3.0 NaN 
d 4.0 NaN 
e 5.0 NaN 
f NaN NaN 

答えて

1

filter機能の使用:

row_index = ['c', 'd', 'e', 'f'] 
col_index = ['x', 'z'] 

df1.filter(row_index, axis=0).filter(col_index, axis=1) 
# x 
#c 3 
#d 4 
#e 5 
3

私はあなたがIndex.intersectionが必要だと思う:

a = ['c', 'd', 'e', 'f'] 
b = ['x', 'z'] 

print (df1.index.intersection(a)) 
Index(['c', 'd', 'e'], dtype='object') 

print (df1.columns.intersection(b)) 
Index(['x'], dtype='object') 

df2 = df1.loc[df1.index.intersection(a),df1.columns.intersection(b)] 
print (df2) 
    x 
c 3 
d 4 
e 5 
1

私はあなただけの行をドロップすることができると信じてとすべてのニューを含む列llの値。

>>> df1.loc[['c', 'd', 'e', 'f'], ['x', 'z']].dropna(how='all').dropna(how='all', axis=1) 
    x 
c 3 
d 4 
e 5 
関連する問題