簡體   English   中英

Pandas slice_replace 與系列

[英]Pandas slice_replace with series

當前slice_replace方法不接受pd.Series作為repl參數:

MWE:

# Example as in the doc
pd.Series(['azerty_0', 'azerty_1']).str.slice_replace(1, 3, repl='repl')
Out[28]: 
0    areplrty_0
1    areplrty_1
dtype: object

# Passing a pd.Series does all combinations
pd.Series(['azerty_0', 'azerty_1']).str.slice_replace(1, 3, repl=pd.Series(['repl_0', 'repl_1']))
Out[29]: 
0    0    arepl_0rty_0
1    arepl_1rty_0
dtype: object
1    0    arepl_0rty_1
1    arepl_1rty_1
dtype: object
dtype: object

# Expected result
pd.Series(['azerty_0', 'azerty_1']).str.slice(0, 1) + pd.Series(['repl_0', 'repl_1']) + pd.Series(['azerty_0', 'azerty_1']).str.slice(3)
Out[30]: 
0    arepl_0rty_0
1    arepl_1rty_1
dtype: object

有沒有更好的方法來實現這個結果?

找不到任何更好的替代方案,您可以使用它代替切片功能的一個是在 str 上進行列表切片,即

s = pd.Series(['azerty_0', 'azerty_1']) 
rep = pd.Series(['repl_0', 'repl_1'])

new = s.str[:1]+ rep +s.str[3:]

另一個班輪是:

new = s.str.partition('ze').rename(columns={1:'x'}).assign(x=rep).sum(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM