Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas/numpy np.where(df[';x';].str.contains(';y';)与np.where(df[';x';])对比_Python_String_Pandas_Numpy_Where - Fatal编程技术网

Python pandas/numpy np.where(df[';x';].str.contains(';y';)与np.where(df[';x';])对比

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'的行 我错过了什么?为什么第一种形式失败

作为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'
的行


我错过了什么?为什么第一种形式失败了?(Python 2.7)

这些是不同的操作:

  • 检查中的
    将搜索是否有任何元素等于
    'y'
    。(注意:对于可能无法正常工作的
    str
    ing的
    系列

  • .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