首页 文章

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

提问于
浏览
2

我是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 回答

  • 1

    避免链式索引

    这种操作称为链式索引,它是 explicitly discouraged in the docs

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

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

    mask = (df['kind'] == 'dog') & (df['colour'] == '')
    df.loc[mask, 'colour'] = 'black'
    

    使用字典表示可变数量的变量

    这种操作在Python中起作用 not

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

相关问题