我是 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))
最佳答案
避免链式索引
这种操作称为链式索引,它是 explicitly discouraged in the docs :
df[(df['kind'] == 'dog') & (df['colour'] == '')].at['colour'] = 'black'
相反,计算然后使用 bool 掩码:
mask = (df['kind'] == 'dog') & (df['colour'] == '')
df.loc[mask, 'colour'] = 'black'
为可变数量的变量使用字典
这种操作在 Python 中不有效:
new_colour_dog = 'polka dots'
new_colour+'_dog' # want 'polka dots', but will not work
改用字典:
new_colours = {'dog': 'polka dots', 'cat': 'plaid', 'bird': 'stripes'}
然后您可以迭代字典的键值对:
for animal, new_colour in new_colours.items():
mask = (df['kind'] == animal) & (df['colour'] == '')
df.loc[mask, 'colour'] = new_colour
当 mask
返回一系列 False
值时,您不需要测试/特殊情况实例。
关于python - 使用 Pandas Dataframe 在 python for 循环中保存更新的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698343/