2016-06-16 4 views
3

분류 할 텍스트 데이터가 있습니다. 개별 문자열을 지정하는 for 루프를 사용하여 특정 단어 나 구가 다른 열의 행에 있는지 식별합니다. true이면 루프가 새 값에 특정 값을 추가합니다. 그런 다음 새 목록이 DataFrame에 추가됩니다. 그러나이 방법은 수많은 테스트를 위해 수많은 문자열을 지정해야하므로 실제 데이터에는 너무 다루기 힘듭니다.루프에서 각 문자열을 개별적으로 참조하지 않고 for 루프에서 문자열을 검색합니다.

루프가 검색 할 수있는 단일 데이터 구조 내에서 개별 문자열을 그룹화 할 수있는 방법이 있습니까? 루프의 각 테스트가 의미하는 바는 루프 내부에서 철자가 지정된 개별 문자열과 달리 하나의 데이터 구조 만 참조합니다. 이 작업을 수행 할 수 있습니까?

다음은 현재 수행중인 작업의 재현 가능한 예입니다. 이 루프에 대한 다음과 같은 분류를 수행 그리고

opinion 
0 He said it was too expensive 
1 She said it was too costly 
2 He thought it was not fast enough 
3 They thought is was not right and too much money 
4 Her view was that it was too small and too slow 

:

data = { 
     'opinion': ['He said it was too expensive', 
         'She said it was too costly', 
         'He thought it was not fast enough', 
         'They thought is was not right and too much money', 
         'Her view was that it was too small and too slow', 
        ]} 

df = pd.DataFrame(data, columns = ['opinion']) 
df 

이를 만듭니다.

new_col=[] 

for row in df['opinion']: 
    if 'too expensive' in row or 'too costly' in row or 'too much money' in row: 
     new_col.append('Too Expensive') 
    elif 'not fast enough' in row or 'too slow' in row: 
     new_col.append('Too Slow') 

df['reason'] = new_col 
df 

    opinion           reason 
0 He said it was too expensive      Too Expensive 
1 She said it was too costly      Too Expensive 
2 He thought it was not fast enough     Too Slow 
3 They thought is was not right and too much money Too Expensive 
4 Her view was that it was too small and too slow Too Slow 

실제 데이터에는 각 테스트마다 루프 내부에 개별 문자열 점수를 쓸 수는 없지만 실제로는 너무 많습니다.

답변

2

당신은 keysreplacementvalues 있습니다 dictionarieslist, 당신의 조건을 유지할 수 단어 to_replacelists 포함되어 있습니다.

words = [{'Too Expensive': ['too expensive', 'too costly', 'too much money'], 
     'Too Slow': ['not fast enough', 'too slow']}] 

그런 다음 words 이상 loop은 한 번에 모든 to_replace에 보이는 regexstr.contains를 사용하고 .loc[] 파악하고 할당합니다.
for word in words: 
    for replacement, to_replace in word.items(): 
     df.loc[df.opinion.str.contains('|'.join(to_replace)), 'reason'] = replacement 

는 얻을 :

          opinion   reason 
0      He said it was too expensive Too Expensive 
1      She said it was too costly Too Expensive 
2     He thought it was not fast enough  Too Slow 
3 They thought is was not right and too much money Too Expensive 
4 Her view was that it was too small and too slow  Too Slow 
1

이 작동합니다 :

test_strings = ['too expensive', 'too costly', 'too much money'] 
for row in df['opinion']: 
    for tester in test_strings: 
     if tester in row: 
      new_col.append("Too Expensive") 
      break 
+2

당신은'너무 Slow'에 대해 잊어 버려. – jezrael

+0

MWE가 충분하다고 생각했습니다. – VBB

0

을 내가 정규식이 경우에 더 convinient 것 사용하여 생각 : 그래서 .apply입니다

df['reason'] = '' 

df.ix[df.opinion.str.lower().str.contains(r'too\s+(?:expensive|costly|much money)'), 'reason'] = 'Too Expensive' 

df.ix[df.opinion.str.lower().str.contains(r'(?:not fast enough|too slow)'), 'reason'] = 'Too Slow' 

In [309]: df 
Out[309]: 
              opinion   reason 
0      He said it was too expensive Too Expensive 
1      She said it was too costly Too Expensive 
2     He thought it was not fast enough  Too Slow 
3 They thought is was not right and too much money Too Expensive 
4 Her view was that it was too small and too slow  Too Slow 
0

팬더 행에 기능을 적용하기위한 빠른 솔루션을 꽤 많이 이것을 위해 설계되었습니다. 이상적으로는 벡터화가 가장 빠르지 만 그렇게 할 수있는 방법을 생각할 수 없습니다. .apply는 그 이후이며 행을 반복하는 것이 가장 느린 것이므로 가능한 한 그것을 피하는 것이 가장 좋습니다.

잠재적 인 키워드 목록을 확장하는 편리한 방법으로 키워드 목록에 사전을 사용하는 것이 좋습니다.

def categorizer(x): 
main_dict = {"too much money":"too expensive", "too expensive":"too expensive", "too costly":"too expensive", "too slow":"too slow", "not fast enough": "not fast enough"} 
for key in main_dict: 
    if key in x: 
     return main_dict[key] 
df["Category"] = df["opinion"].apply(lambda x:categorizer(x)) 
+0

'.apply'만으로 반복 작업을 수행하지 않습니까? 나는 그것이 반복보다 빠르다고 생각하지 않았다. – itzy

+1

아니요 .apply는 행/열 단위로 작동합니다. .applymap은 여러분이 생각하고있는 것으로, 요소 단위로 작동합니다. .apply vs iterrows를 사용하면 큰 데이터 세트에서 상당한 속도 향상을 얻을 수 있습니다. – Yarnspinner

관련 문제