48
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

【Python】pandas.DataFrameで複数条件指定時のエラーの対処

pandas.DataFrameで複数条件を指定したときによく出るエラーの対処方法。

準備
import numpy as np
import pandas as pd

cols = ['var1', 'var2', 'var3', 'var4']
df = pd.DataFrame(np.random.randn(4, 4), columns=cols)
df

       var1      var2      var3      var4
0  0.597118 -0.853204  1.813645  0.694750
1 -1.118426  0.011119 -2.161933  0.792262
2  0.665828  0.384975  1.676278 -0.487037
3 -0.216118  2.084042 -0.279242 -1.785128
エラーその1
df[df['var1'] >= 0 and df['var2'] <= 0.5]

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
エラーその2
df[(df['var1'] >= 0) and (df['var2'] <= 0.5)]

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
エラーその3
df[df['var1'] >= 0 & df['var2'] <= 0.5]

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
上手くいくパターン
df[(df['var1'] >= 0) & (df['var2'] <= 0.5)]

       var1      var2      var3      var4
0  0.597118 -0.853204  1.813645  0.694750
2  0.665828  0.384975  1.676278 -0.487037

要するに,「条件ごとに括弧で括る」+「&で接続」ということですね。

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
48
Help us understand the problem. What are the problem?