2017-03-24 5 views
1

위도와 경도 좌표를 비롯한 기존 데이터 프레임 ("radar_locations")이 있습니다. 해당 정보에, 나는 국가와 국가 열을 추가해야합니다, 그래서 나는 역 지오 코딩을 수행하고 난 dataframe에 새로운 컬럼에 값을 할당 할 때언 패킹 기능이 pandas 데이터 프레임 열로 반환됩니다.

return geodata.state, geodata.country을 필요로하는 두 개의 값을 반환하는 함수를 작성했습니다 압축을 풀 값이 너무 많아서 오류가 발생합니다. 그러나 함수가 단일 값을 반환하도록 코드를 업데이트하면 새 값을 새 데이터 프레임 열에 성공적으로 쓸 수 있습니다.

팬더의 이별이나 뭔가 더 근본적인 것이 있다면 내가 누락 되었습니까?

def reverse_geocode(lat, long): 
    ... 
    return geodata.country 

radar_locations['Country'] = radar_locations.apply(lambda x: reverse_geocode(x[1], x[0]), axis=1) 

작동

def reverse_geocode(lat, long): 
    ... 
    return geodata.state, geodata.country 

state, country = reverse_geocode(mylat, mylong) 

실패 작동

def reverse_geocode(lat, long): 
    ... 
    return geodata.state, geodata.country 

radar_locations['State'], radar_locations['Country'] = radar_locations.apply(lambda x: reverse_geocode(x[1], x[0]), axis=1) 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-28-82e3c63a2ecb> in <module>() 
    19   raise 
    20 
---> 21 radar_locations['State'], radar_locations['Country'] = radar_locations.apply(lambda x: reverse_geocode(x[1], x[0]), axis=1) 

ValueError: too many values to unpack (expected 2) 

답변

2

사용 zip* 운영자는 압축을 풀고 할당을 수행 할 수

# A function that returns multiple things. 
def some_func(x): 
    return x+1, x+2 

# Example DataFrame 
df = pd.DataFrame({'A': range(5)}) 

# Example usage. 
df['B'], df['C'] = zip(*df['A'].apply(some_func)) 

결과 출력 :

A B C 
0 0 1 2 
1 1 2 3 
2 2 3 4 
3 3 4 5 
4 4 5 6 

apply에서 직접 할당하는 노력과 함께 문제는 여러 값을 반환 할 때, 당신이 실제로있어 것입니다 두 개의 개별 열이 아닌 하나의 튜플 열을 반환하기 때문에 압축 풀기 프로세스가 필요한 이유는 다음과 같습니다.

df['A'].apply(some_func) 

0 (1, 2) 
1 (2, 3) 
2 (3, 4) 
3 (4, 5) 
4 (5, 6) 
+0

그 트릭을 수행했습니다. 많은 감사, @ 뿌리. – Barrett

관련 문제