Python 解包函数返回数据帧列

Python 解包函数返回数据帧列,python,pandas,Python,Pandas,我有一个现有的数据框(“雷达位置”),其中包含(除其他外)纬度和经度坐标。为了获得这些信息,我需要添加一个country和state列,因此我编写了一个函数,该函数执行反向地理编码,并返回所需的两个值return geodata.state,geodata.country 当我尝试将值分配到dataframe中的新列时,我得到一个错误,即有太多的值需要解包。但是如果我更新代码,使函数返回单个值,我就可以成功地将该值写入新的dataframe列 如果这只是熊猫的一种怪癖,或者我还缺少一些更基本的东

我有一个现有的数据框(“雷达位置”),其中包含(除其他外)纬度和经度坐标。为了获得这些信息,我需要添加一个country和state列,因此我编写了一个函数,该函数执行反向地理编码,并返回所需的两个值
return geodata.state,geodata.country

当我尝试将值分配到dataframe中的新列时,我得到一个错误,即有太多的值需要解包。但是如果我更新代码,使函数返回单个值,我就可以成功地将该值写入新的dataframe列

如果这只是熊猫的一种怪癖,或者我还缺少一些更基本的东西

有效

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.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)
def反向地理编码(横向、纵向):
...
返回geodata.state、geodata.country
雷达位置['State'],雷达位置['Country']=雷达位置。应用(λx:反向地理代码(x[1],x[0]),轴=1)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
19提高
20
--->21雷达位置['State'],雷达位置['Country']=雷达位置。应用(λx:反向地理代码(x[1],x[0]),轴=1)
ValueError:要解压缩的值太多(应为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)