python中矩阵中的多字符替换

时间:2017-05-29 13:44:43

标签: python-3.x pandas

我还在学习python,我有一个属于一个非常大的矩阵的向量,这个向量中的条目是对象类型。它们是('<1年','1年','2年'等等) 我想将它分别改为0,1,2,3。我编写了以下几行,但必须有更简单的解决方案,不需要有10个条件的循环:

import numpy as np
import pandas as pd

data_file = pd.read_csv('loan.csv')

emp_length=data_file.emp_length
emp_len=[]
for i in range(len(emp_length)):
   if emp_length[i]=='< 1 year':
       emp_len.append(0)
   elif emp_length[i]=='1 year':
       emp_len.append(1)
   elif emp_length[i]=='2 years':
       emp_len.append(2)
   elif emp_length[i]=='3 years':
       emp_len.append(3)
   elif emp_length[i]=='4 years':
       emp_len.append(4)
   elif emp_length[i]=='5 years':
       emp_len.append(5)
   elif emp_length[i]=='6 years':
       emp_len.append(6)
   elif emp_length[i]=='7 years':
       emp_len.append(7)
   elif emp_length[i]=='8 years':
       emp_len.append(8)
   elif emp_length[i]=='9 years':
       emp_len.append(9)
   elif emp_length[i]=='10+ years':
       emp_len.append(10)
   else:
       emp_len.append(0)

我不需要创建新的载体,但这是我自己想出的解决方案。如果无论如何都要在同一个向量中替换那些条目,那就更好了。感谢您提出任何建议和帮助

1 个答案:

答案 0 :(得分:2)

考虑数据框df

np.random.seed([3,1415])
df = pd.DataFrame(dict(emp_length=np.random.choice(list(m.keys()), 20)))
print(df)

   emp_length
0    < 1 year
1     2 years
2   10+ years
3   10+ years
4     7 years
5   10+ years
6     3 years
7     8 years
8     7 years
9   10+ years
10   < 1 year
11    6 years
12    8 years
13    6 years
14   < 1 year
15  10+ years
16    2 years
17   < 1 year
18    4 years
19    9 years

您可以将mapreplace与字典

一起使用
m = {
   '< 1 year': 0,
   '1 year': 1,
   '2 years': 2,
   '3 years': 3,
   '4 years': 4,
   '5 years': 5,
   '6 years': 6,
   '7 years': 7,
   '8 years': 8,
   '9 years': 9,
   '10+ years': 10
}

data_file.emp_length.map(m)
# or equivalently
# data_file.emp_length.replace(m)

0      0
1      2
2     10
3     10
4      7
5     10
6      3
7      8
8      7
9     10
10     0
11     6
12     8
13     6
14     0
15    10
16     2
17     0
18     4
19     9
Name: emp_length, dtype: int64

您还可以使用分类类型

cats = ['< 1 year', '1 year', '2 years', '3 years', '4 years', '5 years', '6 years', '7 years', '8 years', '9 years', '10+ years']
c = df.emp_length.astype('category', categories=cats, ordered=True)
print(c)

0      < 1 year
1       2 years
2     10+ years
3     10+ years
4       7 years
5     10+ years
6       3 years
7       8 years
8       7 years
9     10+ years
10     < 1 year
11      6 years
12      8 years
13      6 years
14     < 1 year
15    10+ years
16      2 years
17     < 1 year
18      4 years
19      9 years
Name: emp_length, dtype: category
Categories (11, object): [< 1 year < 1 year < 2 years < 3 years ... 7 years < 8 years < 9 years < 10+ years]

然后你可以用

访问映射的整数
c.cat.codes

0      0
1      2
2     10
3     10
4      7
5     10
6      3
7      8
8      7
9     10
10     0
11     6
12     8
13     6
14     0
15    10
16     2
17     0
18     4
19     9
dtype: int8
相关问题