[英]Python function partial string match
我有一個這樣的熊貓數據框:
a b c
foo bar baz
bar foo baz
foobar barfoo baz
我在python中定義了以下函數:
def somefunction (row):
if row['a'] == 'foo' and row['b'] == 'bar':
return 'yes'
return 'no'
它工作得很好。 但是我需要對if
函數進行一些細微調整,以考慮partial string
匹配。
我嘗試了幾種組合,但似乎無法正常工作。 我收到以下錯誤:
("'str' object has no attribute 'str'", 'occurred at index 0')
我嘗試的功能是:
def somenewfunction (row):
if row['a'].str.contains('foo')==True and row['b'] == 'bar':
return 'yes'
return 'no'
將contains
用作布爾掩碼,然后使用numpy.where
:
m = df['a'].str.contains('foo') & (df['b'] == 'bar')
print (m)
0 True
1 False
2 False
dtype: bool
df['new'] = np.where(m, 'yes', 'no')
print (df)
a b c new
0 foo bar baz yes
1 bar foo baz no
2 foobar barfoo baz no
或者,如果還需要檢查b
列中的子字符串:
m = df['a'].str.contains('foo') & df['b'].str.contains('bar')
df['new'] = np.where(m, 'yes', 'no')
print (df)
a b c new
0 foo bar baz yes
1 bar foo baz no
2 foobar barfoo baz yes
如果需要自定義功能,在更大的DataFrame
應該更DataFrame
:
def somefunction (row):
if 'foo' in row['a'] and row['b'] == 'bar':
return 'yes'
return 'no'
print (df.apply(somefunction, axis=1))
0 yes
1 no
2 no
dtype: object
def somefunction (row):
if 'foo' in row['a'] and 'bar' in row['b']:
return 'yes'
return 'no'
print (df.apply(somefunction, axis=1))
0 yes
1 no
2 yes
dtype: object
時間 :
df = pd.concat([df]*1000).reset_index(drop=True)
def somefunction (row):
if 'foo' in row['a'] and row['b'] == 'bar':
return 'yes'
return 'no'
In [269]: %timeit df['new'] = df.apply(somefunction, axis=1)
10 loops, best of 3: 60.7 ms per loop
In [270]: %timeit df['new1'] = np.where(df['a'].str.contains('foo') & (df['b'] == 'bar'), 'yes', 'no')
100 loops, best of 3: 3.25 ms per loop
df = pd.concat([df]*10000).reset_index(drop=True)
def somefunction (row):
if 'foo' in row['a'] and row['b'] == 'bar':
return 'yes'
return 'no'
In [272]: %timeit df['new'] = df.apply(somefunction, axis=1)
1 loop, best of 3: 614 ms per loop
In [273]: %timeit df['new1'] = np.where(df['a'].str.contains('foo') & (df['b'] == 'bar'), 'yes', 'no')
10 loops, best of 3: 23.5 ms per loop
您的例外可能是因為您編寫
if row['a'].str.contains('foo')==True
刪除“ .str”:
if row['a'].contains('foo')==True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.