4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

データフレームからの条件要素抽出:Rは%in%、Pythonは.isin()

Last updated at Posted at 2020-10-13

Rユーザーの私がpythonを書く上で頻繁にど忘れしてしまう操作をメモしておく。
"R %in% in python"などと都度検索しても欲しい情報にすぐにたどり着けなかったため。

特定の列が複数の要素のいずれかにマッチする行を抽出する

データフレーム: iris
特定の列名: Species
複数の要素: cond ("setosa"もしくは"virginica"のみ抽出)

Rで%in%演算子を使って書ける操作は、

### R ###
library(dplyr)

cond <- c("setosa", "virginica")
df <- iris %>% dplyr::filter(., Species %in% cond)

Pandasだと.isin()で書ける。

### python ###
import pandas as pd
from sklearn import datasets

### iris データセット準備
iris_sk = datasets.load_iris()
iris = pd.DataFrame(iris_sk.data, columns=iris_sk.feature_names)
iris['Species'] = iris_sk.target_names[iris_sk.target]

cond = ["setosa", "virginica"]
df = iris[iris["Species"].isin(cond)]

マッチする行を除外したい場合は、それぞれ!~を使う。

### R ###
df2 <- iris %>% dplyr::filter(., !Species %in% cond)
### Python ###
df2 = iris[~iris["Species"].isin(cond)]
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?