为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Pandas Dataframe 保存在 python for 循环中更新的值

使用 Pandas Dataframe 保存在 python for 循环中更新的值

泛舟湖上清波郎朗 2021-09-11 19:38:19
我是 Python 和 Pandas 的新手,我正在尝试用特定值替换数组中的所有空值。每次我运行它时,更新的值都不会持续存在。我已经看到 Pandas 在迭代行时不会保存更改……那么我该如何保存更改?这是我的代码animal_kinds = set(df.AnimalKind) # this gives categories used below in the "ak" like dog, cat, birdnew_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 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

避免链式索引

这种操作称为链式索引,文档中明确不鼓励这样做:


df[(df['kind'] == 'dog') & (df['colour'] == '')].at['colour'] = 'black'

相反,计算然后使用布尔掩码:


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值时,您不需要测试/特殊情况实例。


查看完整回答
反对 回复 2021-09-11
  • 1 回答
  • 0 关注
  • 271 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信