熊貓需要特定的語法才能工作。使用運算符in查找str
y
檢查字符串y
在熊貓Series
中的成員身份。
>>> df = pd.DataFrame({'x': ['hiya', 'howdy', 'hello']})
>>> df
x
0 hiya
1 howdy
2 hello
>>> df_rows = np.where('y' in df['x'])[0]
>>> df_rows
array([], dtype=int64)
>>> df_rows = np.where(df['x'].str.contains('y'))[0]
>>> df_rows
array([0, 1], dtype=int64)
試試這個,注意它返回一個布爾值,而不是三個(像我們可能會首先想到,因爲有該系列三個項目):
>>> 'y' in df['x']
False
>>> 'hiya' in df['x']
False
>>> 'hiya' in df['x'].values
True
你總是需要考慮到自己:「我正在尋找系列中的物品,還是我正在尋找系列內物品中的字符串?「
對於在一系列項目,使用isin
:
df['x'].isin(['hello'])
對於字符串的項目內,使用.str.{whatever}
(或.apply(lambda s: s)
):在所述第一,`DF
>>> df['x'].str.contains('y')
0 True
1 True
2 False
Name: x, dtype: bool
>>> df['x'].apply(lambda s: 'y' in s)
0 True
1 True
2 False
Name: x, dtype: bool
[ 'X'] '是一個列表式的序列,你正在尋找正好是''''的條目。在第二個中,'df ['x']。str'將類似字符串的操作向'df ['x']' –