import pandas as pd
data = ["a", "b", "c"]
df = pd.DataFrame(data)
flag = df[0].isin(["a"])
print(df[flag])
実行結果
0
0 a
ちなみにisinの引数は「リスト」ですので、値だけ書いた場合はエラーとなります。
import pandas as pd
data = ["a", "b", "c"]
df = pd.DataFrame(data)
print(df[0].isin("a"))
実行結果
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[25], line 7
3 data = ["a", "b", "c"]
5 df = pd.DataFrame(data)
----> 7 print(df[0].isin("a"))
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/core/series.py:5559, in Series.isin(self, values)
5486 def isin(self, values) -> Series:
5487 """
5488 Whether elements in Series are contained in `values`.
5489
(...)
5557 dtype: bool
5558 """
-> 5559 result = algorithms.isin(self._values, values)
5560 return self._constructor(result, index=self.index, copy=False).__finalize__(
5561 self, method="isin"
5562 )
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/core/algorithms.py:477, in isin(comps, values)
472 raise TypeError(
473 "only list-like objects are allowed to be passed "
474 f"to isin(), you passed a `{type(comps).__name__}`"
475 )
476 if not is_list_like(values):
--> 477 raise TypeError(
478 "only list-like objects are allowed to be passed "
479 f"to isin(), you passed a `{type(values).__name__}`"
480 )
482 if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)):
483 orig_values = list(values)
TypeError: only list-like objects are allowed to be passed to isin(), you passed a `str`
コメント