我是Python和Pandas的新手,我正在尝试用特定值替换数组中的所有空值 .
每次运行此操作时,更新的值都不会保留 .
我已经看到Pandas在迭代行时没有保存更改...那么如何保存更改呢?
这是我的代码
animal_kinds = set(df.AnimalKind) # this gives categories used below in the "ak" like dog, cat, bird
new_color_dog = 'polka dots'
new_color_cat = 'plaid'
new_color_bird = 'stripes'
for ak in animal_kinds:
ak_colors = ak['colors']
ak_with_no_color = animals[(df["Kind"] == ak ) & (df["Color"] == "" ) ]
result_count = len(ak_with_no_color)
if result_count:
ak_with_no_color.at["Color"] = new_color_ak #sets new color based on kind of animal (ak)
print(str(ak) 'color is changed to ' + str(new_color_ak))
1 回答
避免链式索引
这种操作称为链式索引,它是 explicitly discouraged in the docs :
相反,计算然后使用布尔掩码:
使用字典表示可变数量的变量
这种操作在Python中起作用 not :
改为使用字典:
然后,您可以迭代字典的键值对:
当
mask
返回一系列False
值时,您不需要测试/特殊情况实例 .