2
私はまだPythonを学んでおり、かなり大きな行列に属するベクトルがあり、このベクトルのエントリはオブジェクト型です。それらは( '< 1年'、 '1年'、 '2年'など) それぞれ0,1,2,3に変更したいと思います。私は仕事に以下の行を書きましたが、10回の条件でループを必要としない、より簡単な解決策が存在しなければならない:Pythonの行列で複数の文字を置換する
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)
私は新しいベクトルを作成する必要はありませんが、これは私がいたソリューションでした自分で思いつくことができる。同じベクター内のそれらのエントリーを置き換えることができれば、さらに良いでしょう。任意の提案をありがとうと
偉大でマッピングされた整数をアクセスすることができました!私はpd.factorizeはうまくいかないと思いますが、「10 +年」の場合は1を返しますが、マップは非常に役に立ちました。 –
回答が役に立ちましたら、[受け入れる](http: /meta.stackexchange.com/a/5235/295067)それ。ありがとう。 – jezrael
それは素晴らしい答えです! – MaxU