[英]How to extract specific text from a pandas column
我有一個 pandas dataframe 有一個列,我需要清理它,因為數據沒有必要的格式:
df = pd.DataFrame({'item': ["1","2","3","4","5","6"], 'store': ["a [note 3]","b [note 98]","c ","a
[note 222]","b","c"]})
print(df)
item store
0 1 a [note 3]
1 2 b [note 98]
2 3 c
3 4 a [note 222]
4 5 b
5 6 c
列'store'
必須像這樣更改:
item store
0 1 a
1 2 b
2 3 c
3 4 a
4 5 b
5 6 c
按左方括號拆分並在結果列表中選擇第一個索引值。
df['store'] = df.store.str.split('\[').str[0]
您不需要正則表達式。 只需在空間上拆分並取第一個字符。
df['store'] = df['store'].apply(lambda x: x.split()[0])
如果你最終需要正則表達式,你可以使用 extract
df['store'] = df['store'].str.extract('^([a-z])')
如果括號前有多個字符
df['store'] = df['store'].str.extract('^(.+?)(?=\[|$)')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.