I checked a few of them. The @ A-Za-z proposal is a significant improvement, but it may be possible to do it even faster.
edit. , dict dataframe ( ). :
- : 11.71
- @A-Za-z: 4.72 , 60%.
- @piRSquared: 4,95 , 58%.
- : 2,81 , 76%.
, :
" . 15 , @A-Za-z 8-9 , 6 . . . ."
import pandas as pd
import re
import timeit
:
miscdict = {" isn't ": ' is not '," aren't ":' are not '," wasn't ":' was not '," snevada ":' Sierra Nevada '}
data=pd.DataFrame({"q1":["beer is ok","beer isn't ok","beer wasn't available"," snevada is good"]})
def org(printout=False):
def parse_text(data):
for key, replacement in miscdict.items():
data['q1'] = data['q1'].str.replace( key, replacement )
return data
data2 = parse_text(data)
if printout:
print(data2)
org(printout=True)
print(timeit.timeit(org, number=10000))
11,7 :
q1
0 beer is ok
1 beer is not ok
2 beer was not available
3 Sierra Nevada is good
11.71043858179268
@A-Za-z:
miscdict = {" isn't ": ' is not '," aren't ":' are not '," wasn't ":' was not '," snevada ":' Sierra Nevada '}
data=pd.DataFrame({"q1":["beer is ok","beer isn't ok","beer wasn't available"," snevada is good"]})
def alt1(printout=False):
data['q1'].replace(miscdict, regex = True, inplace = True)
if printout:
print(data)
alt1(printout=True)
print(timeit.timeit(alt1, number=10000))
4,7 :
q1
0 beer is ok
1 beer is not ok
2 beer was not available
3 Sierra Nevada is good
4.721581550644499
@piRSquared:
miscdict = {" isn't ": ' is not '," aren't ":' are not '," wasn't ":' was not '," snevada ":' Sierra Nevada '}
data=pd.DataFrame({"q1":["beer is ok","beer isn't ok","beer wasn't available"," snevada is good"]})
def alt2(printout=False):
data = data.replace(miscdict, regex = True)
if printout:
print(data)
alt2(printout=True)
print(timeit.timeit(alt2, number=10000))
5,0 :
q1
0 beer is ok
1 beer is not ok
2 beer was not available
3 Sierra Nevada is good
4.951810616074919
miscdict = {" isn't ": ' is not '," aren't ":' are not '," wasn't ":' was not '," snevada ":' Sierra Nevada '}
miscdict_comp = {re.compile(k): v for k, v in miscdict.items()}
data=pd.DataFrame({"q1":["beer is ok","beer isn't ok","beer wasn't available"," snevada is good"]})
def alt3(printout=False):
def parse_text(text):
for pattern, replacement in miscdict_comp.items():
text = pattern.sub(replacement, text)
return text
data["q1"] = data["q1"].apply(parse_text)
if printout:
print(data)
alt3(printout=True)
print(timeit.timeit(alt3, number=10000))
2,8 :
q1
0 beer is ok
1 beer is not ok
2 beer was not available
3 Sierra Nevada is good
2.810334940701157
, , .
: https://jerel.co/blog/2011/12/using-python-for-super-fast-regex-search-and-replace