2017-11-13 12 views
2

私は123-0-1を持っていて、この値がリスト内に存在するかどうかをチェックしたいとします。私が使用するSQLでリストに値が存在するか確認してください

df = [ 
     {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, 
     {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'} 
     ] 

::以下は私が持っているリストがある

select mpls, source from df where source = 192.168.10.10 

リストから、私は正しい宛先を得ることができるようなソース192.168.10.10から抽出MPLS 123-0-1をしたいと思います12.168.100.10

答えて

2

dfはデータフレームではありません。これは辞書のリストです。このように

、あなたの唯一のオプションは、ループとif条件である:

for connection in df: 
    if connection['source'] == '192.168.10.10': 
     print(connection['mpls']) 
     print(connection['destination']) 
     # do whatever with connection. Can also break if it is guaranteed to be unique. 


dfデータフレームである場合は、あなたがパンダのインデックス付けの構文を使用することができます

relevant_rows = df[df['source'] == '192.168.10.10'] 

relevant_rowsは、source'192.168.10.10'に等しいローである新しいデータフレームになります。

import pandas as pd 

data = [ 
     {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, 
     {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'} 
     ] 

df = pd.DataFrame(data) 

print(df) 

#   destination  mpls   source 
#  0 12.168.100.10 123-0-1 192.168.10.10 
#  1 10.12.129.200 123-0-1 192.168.10.15 

relevant_rows = df[df['source'] == '192.168.10.10'] 

print(relevant_rows) 

#   destination  mpls   source 
# 0 12.168.100.10 123-0-1 192.168.10.10 
+0

うわー、これは本当に役に立ちます、それは動作します!ありがとうございました !! –

1

なぜデータフレームを作成しないのですか?あなたがリストで作業しているとここで

df = pd.DataFrame(df) 
df[df['source'] == '192.168.10.10'] 
0

は、リストの内包表記を使用して可能な解決策である:

[(x['mpls'], x['destination']) for x in df if x['source'] == '192.168.10.10'] 

それはsourceに基づいmplsdestinationとのタプルを返します:

[('123-0-1', '12.168.100.10')] 
+0

オハイオ州素晴らしい!これで、私は必要なすべてのmplsとdestinationをリストアップすることができます。共有いただきありがとうございます! –

0

他の答えはうまくいきます。ただnextも使用することができる方法を示したかった:これは基準を満たすのみ最初dictionaryを返し

df = [{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}] 

try: 
    target = next(x for x in df if x['source'] == '192.168.10.10') 
except StopIteration: 
    print('Value not found!') 
else: 
    print(target['mpls'])   # -> 123-0-1 
    print(target['destination']) # -> 12.168.100.10 

注こと。 SQLステートメントに基づいて、すべてとしたいと思うようです。

+0

はい、私はそれらをすべて手に入れたいです。共有ありがとう! –

0

filter機能を使用して、フィルタリングされたデータをリストから取得することもできます。 filtered_list = filter((lambda x: x['source'] == '192.168.10.10'), df)

関連する問題