2016-07-20 3 views
1

나는이 (샘플)처럼 보이는 거대한 pandasDataFrame 있습니다pandas col을 사전으로 재 할당해도 원래 DataFrame에는 아무런 영향이 없습니까?

df = pd.DataFrame({"col1":{0:"There ARE NO ERRORS!!!", 1:"EVERYTHING is failing", 2:"There ARE NO ERRORS!!!"}, "col2":{0:"WE HAVE SOME ERRORS", 1:"EVERYTHING is failing", 2:"System shutdown!"}}) 

내가 구두점 스트립와 소문자 문자열을 반환 cleanMessage라는 함수가 있습니다. 예를 들어 cleanMessage("THERE may be some errors, I don't know!!")there may be some errors i dont know을 반환합니다.

col1의 모든 메시지를 cleanMessage이 (해당 메시지 열을 기본적으로 정리하여) 반환하는 것으로 바꾸려고합니다. pd.DataFrame.iterrows 나를 위해 잘 작동하지만 조금 느립니다.

message_set = set(df["col1"]) 
message_dict = dict((original, cleanMessage(original)) for original in message_set) 
df = df.replace("col1", message_dict) 

그래서 원래 df이 좋아하는 것 : 나는 기본적으로 원래 df이 뭔가를 키에 새 값을지도하기 위해 노력하고있어

>>> df 
    col1      col2 
0 "There ARE NO ERRORS"  "WE HAVE SOME ERRORS" 
1 "EVERYTHING is failing" "EVERYTHING is failing" 
2 "There ARE NO ERRORS!!!" "System shutdown!" 

을 그리고 df해야 "후" 나는 내 코드의 replace 부분에 뭔가가

>>> df 
    col1      col2 
0 "there are no errors"  "WE HAVE SOME ERRORS" 
1 "everything is failing" "EVERYTHING is failing" 
2 "there are no errors"  "System shutdown!" 

암 :처럼?

편집 : 미래의 시청자에 대한

, 여기에 내가 일을 가지고 코드입니다 :

df["col1"] = df["col1"].map(message_dict) 
+1

, df.replace는() "COL1"의 모든 인스턴스를 찾고 있습니다 (문자열보다는 시리즈) –

+0

이유는 단지'안양를 [ "COL1"하지 ] = [df [ "col1"]]'에서 s의 cleanMessage (s)? –

+0

@JBr, 그래서 만약 그 칼럼을'replace'하려고한다면 구문은 무엇이되어야합니까? 'df = df.replace (df [ "col1"], message_dict)'? – blacksite

답변

1

replace 잘 작동과 regex이 - 중첩 된 replace()clean message()의 논리를 넣어 고려가.

df["col2"] = df["col1"].replace(...).replace(...) 
0
현재
df.col1 = df.col1.str.lower().str.replace(r'([^a-z ])', '') 

df 

enter image description here

관련 문제