tomoc4 :
나는 내가 원하는 것은 단위 값을 갖는 새 열을 생성하는 또 다른 열 문자열의 값으로 새 열을 만들려고 해요.
단위의 위치는 다를 수 있습니다.
내 문자열의 예입니다
this is a string and we have 4U to use
this is another string 5UN
only 6U to use today
나는 위치가 다를 수 있기 때문에 U와 UN 모두에 가입 된 번호를 추출해야합니다.
df['test_units'] = df['ITEM_DESC'].str.get(r'\(*U.*?\)',)
df['test_units']
이것은 내 정규식하지만 난 단지 유모 값을 반환합니다.
어떻게 그냥 U 또는 UN에 가입있어 수를 반환합니까?
Wiktor Stribiżav :
당신은 사용할 수 있습니다
df['test_units'] = df['ITEM_DESC'].str.extract(r'\b(\d+)UN?\b')
참고 항목 정규식 데모 . 폼 괄호 쌍 이스케이프 참고 캡처 그룹 값으로 반환된다 Series.str.extract
.
정규식 일치 :
\b
- 단어 경계(\d+)
- 그룹 1 : 하나 이상의 숫자U
-U
N?
- 옵션N
\b
- 단어 경계
팬더 시험 :
import pandas as pd
cols={'ITEM_DESC': ['this is a string and we have 4U to use','this is another string 5UN','only 6U to use today']}
df = pd.DataFrame(cols)
df['test_units'] = df['ITEM_DESC'].str.extract(r'\b(\d+)UN?\b')
산출:
>>> df
ITEM_DESC test_units
0 this is a string and we have 4U to use 4
1 this is another string 5UN 5
2 only 6U to use today 6
>>>