我有 df ,其中列中的某些記錄包含前綴,而其中一些不包含。我想更新沒有前綴的記錄。不幸的是,我的腳本為 df 中的每條記錄添加了所需的前綴:
new_list = []
prefix = 'x'
for ids in df['ids']:
if ids.find(prefix) < 1:
new_list.append(prefix ids)
如何省略帶有前綴的記錄?我已經嘗試過使用 df[df['ids'].str.contains(prefix)],但出現錯誤。
uj5u.com熱心網友回復:
使用Series.str.startswith蒙版,并加入值numpy.where:
df = pd.DataFrame({'ids':['aaa','ssx','xwe']})
prefix = 'x'
df['ids'] = np.where(df['ids'].str.startswith(prefix), '', prefix) df['ids']
print (df)
ids
0 xaaa
1 xssx
2 xwe
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360277.html
上一篇:每小時行數
