나는 그것을 일로 변환하고 싶은 월과 년을 가진 데이터 프레임을 가지고 있습니다.
Name details
prem 6 months probation included
shaves 3 years 6 months suspended
geroge 48 hours work time
julvie 4 years 20 days terms included
tiz 80 days work
lamp 44 days work
여기에서 변경하고 싶습니다 3 years as 1095 days, 6 months as 186 days
. 윤년도 포함될 수 있으며, 같은 다른 모든 단어를 제거 probation included, suspended
하고 싶습니다. 모든 결과를 새 열에 표시하고 싶습니다.
예상 결과:
Name details Time
prem 6 months probation included 186 days
shaves 3 years 6 months suspended 1181 days
geroge 48 hours work time 48 hours
julvie 4 years 20 days terms included 1480 days
tiz 80 days work 80 days
lamp 44 days work 44 days
사용 Series.str.extract
숫자에서 가져 오기 년 몽, 스칼라에 의해 다음 여러 들어, 시작 날짜를 지정하지 않기 때문에 (이 예를 들어, 더 정확해야 year=365.2564days
의한) Series.map
의 조건에 의해, 그리고 마지막으로 추가 단위 numpy.where
:
d = {'months': 31, 'years':365, 'hours':1, 'days':1}
df1 = df['details'].str.extract('(\d+)\s+(years|months|hours|days)', expand=True)
df['Time'] = df1[0].astype(float).mul(df1[1].map(d)).astype('Int64').astype(str)
df['Unit'] = np.where(df1[1].isin(['years','months', 'days']), ' days', ' ' + df1[1])
df['Time'] += df.pop('Unit')
print (df)
Name details Time
0 prem 6 months probation included 186 days
1 shaves 3 years suspended 1095 days
2 geroge 48 hours work time 48 hours
3 julvie 4 years terms included 1460 days
4 tiz 80 days work 80 days
5 lamp 44 days work 44 days
편집 : 가능한 여러 단위를 사용할 수 있습니다.
#specified dictionary for extract to days
d = {'months': 31, 'years':365, 'days':1}
#extract anf multiple by dictionary
out = {k: df['details'].str.extract(rf'(\d+)\s+{k}', expand=False).astype(float).mul(d[k])
for k, v in d.items()}
#join together, sum and convert to days with replace 0 days
days = pd.concat(out, axis=1).sum(axis=1).astype(int).astype('str').add(' days').replace('0 days','')
#extract hours
hours = df['details'].str.extract(r'(\d+\s+hours)', expand=False).radd(' ').fillna('')
#join together
df['Time'] = days + hours
print (df)
Name details Time
0 john 2 years 1 months 10 days 15 hours work time 771 days 15 hours
1 prem 6 months probation included 186 days
2 shaves 3 years 6 months suspended 1281 days
3 geroge 48 hours work time 48 hours
4 julvie 4 years 20 days terms included 1480 days
5 tiz 80 days work 80 days
6 lamp 44 days work 44 days
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다