2017-03-01 5 views
2

개인 이름을 가진 팬더 데이터 프레임에 full_name 열이 있습니다. 예를 들어 :팬더 데이터 프레임 용 HumanName 라이브러리 벡터화

Full_Name 

Saumendra Nayak 
Pawan Shinde 
Arun Chopra 
Neil Anderson 

나는 첫 번째, 두 번째와 마지막 이름에이 이름을 구분해야합니다. HumanName (nameparser) 라이브러리를 사용하기로 결정했습니다.

그러나 현재 나의 접근 방식으로 루프를 사용하여 각 열의 각 이름을 해당 구성 요소로 분할해야합니다.

# add blank columns based on unique categories 

df["title"] = "" 
df["first"] = "" 
df["middle"] = "" 
df["last"] = "" 
df["suffix"] = "" 
df["nickname"] = "" 

# Split name for each row and save values in dataframe 

for i in range(df.shape[0]): 
    df.loc[i,7]=HumanName(df.full_Name.loc[i]).title 
    df.loc[i,8]=HumanName(df.full_Name.loc[i]).first 
    df.loc[i,9]=HumanName(df.full_Name.loc[i]).middle 
    df.loc[i,10]=HumanName(df.full_Name.loc[i]).last 
    df.loc[i,11]=HumanName(df.full_Name.loc[i]).suffix 
    df.loc[i,12]=HumanName(df.full_Name.loc[i]).nickname 

필자는 다소 새로운 Python입니다.이 루프는 피하는 것이 좋을 것 같습니다. HumanName 라이브러리가 벡터화 된 방식으로 사용될 수 있다면 위의 코드와 같은 루프에서 설정을 피할 수 있도록 제안 할 수 있습니까?

답변

3

먼저 이름 분해 함수를 작성한 다음 열을 지정하기 전에 구성 요소를 압축 할 수 있습니다.

components = ('title', 'first', 'middle', 'last', 'suffix', 'nickname') 

def name_decomp(n): 
    h_n = HumanName(n) 
    return (getattr(h_n, comp) for comp in components) 

rslts = list(zip(*df.Full_Name.map(name_decomp))) 

for i, comp in enumerate(components): 
    df[comp] = rslts[i] 

>>> df = pd.DataFrame(dict(strings=['calgary', 'vancouver', 'toronto'])) 

>>> df 
    strings 
0 calgary 
1 vancouver 
2 toronto 

>>> class Decomp: 
     def __init__(self, s): 
      self.s = s 
      self.first = s[0] 
      self.last = s[-1] 
      self.len = len(s) 

>>> components = ('first', 'last', 'len') 

>>> def useless_decomp(s): 
     dec_s = Decomp(s) 
     return (getattr(dec_s, comp) for comp in components) 

>>> rslts = list(zip(*df.strings.map(useless_decomp))) 

>>> for i, comp in enumerate(components): 
     df[comp] = rslts[i] 

>>> df 
    strings first last len 
0 calgary  c y 7 
1 vancouver  v r 9 
2 toronto  t o 7 
+0

고마워요 (내가 그 도서관을 가지고 있지 않기 때문에 ) 유사 데모! 나는 당신의 기능을 테스트했고 루프보다 300 배 빠릅니다. 루프를 제거하고 파이썬에서 더 빠른 메소드를 적용하는 데 도움이되는 파이썬 튜토리얼을 제안 해 주시겠습니까? – Enthusiast

+1

@Enthusiast 환영합니다! [Pandas 튜토리얼 페이지] (http://pandas.pydata.org/pandas-docs/stable/tutorials.html)를 훑어 본다면 Tom Austspurger의 [Modern Pandas] (http : //tomaugspurger.github.io/modern-1.html) 시리즈. 행운을 빕니다! – miradulo