Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正在更新熊猫的iterrow中的值_Python_Loops_Pandas_Explicit - Fatal编程技术网

Python 正在更新熊猫的iterrow中的值

Python 正在更新熊猫的iterrow中的值,python,loops,pandas,explicit,Python,Loops,Pandas,Explicit,我正在做一些地理编码工作,我使用selenium屏幕刮取位置地址所需的x-y坐标,我将一个xls文件导入panda dataframe,并希望使用显式循环来更新没有x-y坐标的行,如下所示: for index, row in rche_df.iterrows(): if isinstance(row.wgs1984_latitude, float): row = row.copy() target = row.address_chi

我正在做一些地理编码工作,我使用
selenium
屏幕刮取位置地址所需的x-y坐标,我将一个xls文件导入panda dataframe,并希望使用显式循环来更新没有x-y坐标的行,如下所示:

for index, row in rche_df.iterrows():
    if isinstance(row.wgs1984_latitude, float):
        row = row.copy()
        target = row.address_chi        
        dict_temp = geocoding(target)
        row.wgs1984_latitude = dict_temp['lat']
        row.wgs1984_longitude = dict_temp['long']

我已经阅读并充分意识到iterrow只为我们提供了一个视图,而不是一个用于编辑的副本,但是如果我真的要逐行更新值呢?
lambda
可行吗?

iterrows
返回的行是不再连接到原始数据帧的副本,因此编辑不会更改数据帧。谢天谢地,因为从
iterrows
返回的每个项目都包含当前索引,所以您可以使用该索引访问和编辑数据框的相关行:

for index, row in rche_df.iterrows():
    if isinstance(row.wgs1984_latitude, float):
        row = row.copy()
        target = row.address_chi        
        dict_temp = geocoding(target)
        rche_df.loc[index, 'wgs1984_latitude'] = dict_temp['lat']
        rche_df.loc[index, 'wgs1984_longitude'] = dict_temp['long']

根据我的经验,这种方法似乎比使用像
apply
map
这样的方法慢,但一如既往,如何权衡编码的性能/易用性取决于你自己。

我认为你可以做
rche_df.loc[index,'wgs1984_lation']=dict_temp['lat']
,即,使用索引获取原始数据帧的右侧部分。如果这不起作用,请告诉我,我会尝试找到一个正确的答案。@Marius看起来很有效,谢谢,另一种选择是将数据帧转换为dict,并使用普通for循环进行修改。这个答案对我不起作用(为什么在地球上不…),但这确实起作用:严格来说这不是真的,它们可能不是副本。特别是如果所有列的数据类型都相同,这会给我一个复制警告。最后使用了:难道你不把索引拿回来吗?请参阅@jpp的答案。我从这个答案中的代码中得到的错误是
ValueError:要解包的值太多(预期为2)