Python pandas/numpy np.where(df[';x';].str.contains(';y';)与np.where(df[';x';])对比
作为python和pandas的新手,我尝试:Python pandas/numpy np.where(df[';x';].str.contains(';y';)与np.where(df[';x';])对比,python,string,pandas,numpy,where,Python,String,Pandas,Numpy,Where,作为python和pandas的新手,我尝试: df_rows = np.where('y' in df['x'])[0] for i in df_rows: print df_rows.iloc[i] 没有返回行,但是 df_rows = np.where(df['x'].str.contains('y'))[0] for i in df_rows: print df_rows.iloc[i] 在df['x']中执行并返回了包含'y'的行 我错过了什么?为什么第一种形式失败
df_rows = np.where('y' in df['x'])[0]
for i in df_rows:
print df_rows.iloc[i]
没有返回行,但是
df_rows = np.where(df['x'].str.contains('y'))[0]
for i in df_rows:
print df_rows.iloc[i]
在df['x']
中执行并返回了包含'y'
的行
我错过了什么?为什么第一种形式失败了?(Python 2.7)这些是不同的操作:
- 检查中的
将搜索是否有任何元素等于
。(注意:对于可能无法正常工作的'y'
ing的str
系列
)
方法搜索每个元素的字符串表示形式,如果它包含.str.contains
'y'
True
或False
(这是因为并强制执行它)。第二个方法是普通方法,返回一个包含True
或False
的序列
(因为普通方法可以随心所欲)
Pandas需要特定的语法才能工作。使用运算符查找
str
y
可检查pandas系列中字符串y
的成员资格
>>> 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)
试试这个,它会返回一个bool而不是三个bool(就像我们第一次想到的,因为这个系列中有三个项目):
您总是需要想一想:“我是在系列中查找项目,还是在系列中的项目中查找字符串?”
对于系列中的项目,请使用isin
:
df['x'].isin(['hello'])
对于项目中的字符串,请使用.str.{whatever}
(或.apply(lambda s:s)
):
在第一个示例中,
df['x']
是一个类似列表的序列,您要查找的条目正好是'y'
。在第二种情况下,df['x'].str将类似字符串的操作矢量化到df['x'].
>>> 'y' in df['x']
False
>>> 'hiya' in df['x']
False
>>> 'hiya' in df['x'].values
True
df['x'].isin(['hello'])
>>> 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