LoginSignup
0
1

More than 3 years have passed since last update.

Pythonで特定の条件を満たす要素だけ抽出

Posted at

忘れがちなのでメモ

コード

import pandas as pd

data = [
  {"name": "Taro Tanaka",   "organization": "Example1", "age": 18},
  {"name": "Hanako Yamada", "organization": "Example1", "age": 20},
  {"name": "Ichiro Suzuki", "organization": "Example2", "age": 33},
  {"name": "Michiko Sato",  "organization": "Example2", "age": 50},
  ...
]

# オーソドックスな方法
arr = [
  r for r in data
  if r["organization"] == "Example1" and r["age"] > 18
]
## sort
sorted_arr = sorted(arr, key=lambda x: x["age"])


# pandasを利用
df = pd.DataFrame(data)
arr2 = df[(df["organization"] == "Example2") & (df["age"] > 18)]
## sort
sorted_arr = df[(df["organization"] == "Example2") & (df["age"] > 18)].sort_values('age')
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1