我有一系列熊貓,我想通過檢查列中的字串是否是另一個字串的子字串來過濾它。
例如,
sentence = "hello world"
words = pd.Series(["hello", "wo", "d", "panda"])
然后,我想獲得如下系列(即子字串“hello world”的系列)。
filtered_words = pd.Series(["hello", "wo", "d"])
也許有一些像“應用”之類的方法,但它看起來不像矢量化的東西。
我怎樣才能做到?
uj5u.com熱心網友回復:
沒有矢量化的方法可以做到這一點,你需要回圈。
無論您是使用apply還是map這都會做完全相同的回圈。使用純 Python 串列推導式的稍微快一點的方法。
filtered_words = words[[x in sentence for x in words]]
以下是 40 萬行的計時
%%timeit
w.map(lambda x : x in sentence)
103 ms ± 7.97 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
w.apply(lambda x : x in sentence )
121 ms ± 20.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
[x in sentence for x in w]
85.8 ms ± 3.68 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
注意。apply有時比map(或在誤差范圍內)快,但純 python 如果總是快約 15-25%
uj5u.com熱心網友回復:
讓我們試試
out = words[words.map(lambda x : x in sentence )]
0 hello
1 wo
2 d
dtype: object
uj5u.com熱心網友回復:
怎么樣:
out = words[words.apply(lambda x: x in sentence)]
但是串列理解仍然很快:
out = [w for w in words if w in sentence]
uj5u.com熱心網友回復:
你可以使用串列理解
filtered_words = pd.Series([word for word in words if word in sentence])
或者如你所說,你可以使用 apply
word_mask = words.apply(lambda word: word in sentence)
found_words = word_mask*words
filtered_words = found_words[found_words.astype(bool)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388176.html
上一篇:使用Pythonpandas根據列增量對相同的值進行分組
下一篇:只想要新檔案中的前100個條目
