在python中使用通配符重命名级别

时间:2019-05-10 04:26:12

标签: python

如何在Python中使用通配符匹配替换级别?

我有一列名为多年经验的列,值为

<input type="hidden" name="x" />

同样接近600个等级;

我希望全部

  • “ 0年……”为“ <1”,
  • 1年为“ 1”,
  • 2年为“ 2”,
  • 3年为“ 3”,
  • 4年为“ 4”,
  • 超过5年的“> 5”,

总共提供6个级别。

3 个答案:

答案 0 :(得分:1)

对我有用。

import math

# samples ...
years_of_experience = [
  "0 YEAR, 9 MONTHS", 
  "1 YEAR, 0 MONTHS", 
  "2 YEAR, 1 MONTHS", 
  "5 YEAR, 11 MONTHS"
]

for y in years_of_experience:
  year, month = [int(s) for s in y.split() if s.isdigit()]
  years = math.floor((year * 12 + month) / 12)
  if years < 1:
    print('<1')
  elif years > 4:
    print('>5')
  else:
    print(years)

答案 1 :(得分:1)

myarr = ["0 YEAR, 9 MONTHS", "1 YEAR, 0 MONTHS", "1 YEAR, 1 MONTHS", "1 YEAR, 
10 MONTHS", "1 YEAR, 9 MONTHS", "10 YEAR, 0 MONTHS", "10 YEAR, 1 MONTHS", "10 
YEAR, 10 MONTHS",]
for date in myarr:
    year = int(date.split()[0])
    if year<1:
        print("<1")
    elif year>=5:
        print(">5")
    else:
        print(year)

输出为:

<1
1
1
1
1
> 5
> 5

答案 2 :(得分:0)

发现了这个,也可以

df['Service_Year'] = df['YYMM_of_Service'].str[:2].astype(int)
df['Service_Year'] = pd.cut(df['Service_Year'], bins=[0, 1, 2, 3, 4, 5], labels=['<1','2','3','4','>5'])