2017-11-28 7 views
0

문제에 대한 깔끔한 해결책을 찾으려고합니다. 그래서, 나는 각각 CODE5 및 Code4의 값을 확인하고 싶은 경우는 코드 중 하나가 다음 COUNTRY2의 dataframe 일치 Region.First하는 다섯 번째 열을 생성한다 수행 할 작업을팬더는 데이터 프레임 열을 다른 여러 열과 일치 시켜서 열을 생성합니다.

Code DF 
Code1 Code2 Code3 Code4 Code5 
Eur xxx xxx xxx xxx 
xxx xxx xxx ESP xxx 
ASI xxx xxx xxx xxx 
xxx BRA xxx xxx xxx 
xxx AUS xxx xxx xxx 
xxx xxx NOR xxx xxx 
xxx xxx xxx PRT xxx 
xxx xxx xxx xxx SGP 


Country1 DF 
Country-Code Region 
Eur Europe 
ASI Asia 
BRA America 
AUS Asia 
NOR Europe 

Country2 DF 
Country Code Region 
ESP Europe 
PRT Europe 
SGP Asia 
ASI Asia 

: 나는 세 개의 테이블을 가지고 해당 지역 값을 지역 열에 넣으십시오. Code5에 일치하는 코드가 없으면 Code4로 이동하고, Code3 등이 없으면 Country2 데이터 프레임을 찾아야하고 Code3, Code2 및 Code1은 Country1 데이터 프레임을 살펴야합니다. "xxx"를 분명히하기 위해 다른 3 글자 약어 또는 빈 공간을 사용할 수 있습니다. Country1 DF와 Country2 DF간에 유사한 코드와 지역이있을 수도 있지만 Code4와 Code5가 Country1 df와 일치해서는 안되는 값이 있으므로 일치하는 두 개의 서로 다른 데이터 프레임이 있습니다. 여기의 경우는 EUR입니다. Code1, Code2, Code3은 지역 유럽이지만 Code4, Code5는 통화이며 두 열 중 하나가 유럽으로 매핑되는 것을 원하지 않습니다. 당신은 지능형리스트로이 작업을 수행 할 수

`Code1 Code2 Code3 Code4 Code5 Region 
Eur xxx xxx xxx xxx Europe 
xxx xxx xxx ESP xxx Europe 
ASI xxx xxx xxx xxx Asia 
xxx BRA xxx xxx xxx America 
xxx AUS xxx xxx xxx Asia 
xxx xxx NOR xxx xxx Europe 
xxx xxx xxx PRT xxx Europe 
xxx xxx xxx xxx SGP Europe 
` 
+0

내 기분이 : 나는 country_dict1country_dict2 각각 각 dataframe에 대한 code:region의 매핑을 있다고 가정거야/66377/what-is-the-xy-problem). 이 데이터를 어떻게 얻었습니까? – Sebastian

답변

0

국가 코드 매핑을 저장하는 더 좋은 방법은 사전에 있습니다. 이것이 [XY 문제 (https://meta.stackexchange.com/questions 수 있습니다처럼

def determine_region(row): 
    for item in row[:-3:-1]: 
     if item in country_dict1: 
      return country_dict1.get(item) 
    for item2 in row[-3::-1]: 
     if item2 in country_dict2: 
      return country_dict2.get(item2) 
    return pd.np.nan 

df['Region'] = df.apply(determine_region, axis=1) 
+0

안녕하세요, 필요에 따라 완벽하게 작동했습니다. 고맙습니다. – soky

0

:

def determine_region(df_row): 
    # if else chain to make a decision for each row 
    # or maybe you could use python builtin set to make it 
    # more semantic 

# capture each item into a list with a comprehension 
x = [ determine_region(x) for x in CodeDF ] 
# append the data into a new column named region 
CodeDF.loc[:,'Region'] = pd.Series(x) 

기타 리소스

Appending Column to Pandas DF

List Comprehensions

최종 시나리오는 다음과 같이 할 필요가

Sets and Operations with Sets

+1

대신에'df.apply'를 사용할 수 있습니다. – Sebastian

관련 문제