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

时间:2018-12-10 01:15:00

标签: python python-3.x pandas dataframe for-loop

我是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 个答案:

答案 0 :(得分: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中不起作用:

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