gpt4 book ai didi

python - 如何通过使用条件查找和替换数据框中的值来更新?

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:48 24 4
gpt4 key购买 nike

我的目标是根据其他列的条件查找并替换特定列中的值。并根据具体的行进行替换。

举个例子:

import pandas
data = [['red', 'not done'], ['red', 'not done'], ['green', 'not done']]
df = pandas.DataFrame(data, columns = ['color', 'status'])
print(df)

我们有输出 DataFrame:

   color    status
0 red not done
1 red not done
2 green not done

我的目标是让所有的green 颜色状态都变成done 状态。就像:

   color    status
0 red not done
1 red not done
2 green done

我尝试过的:

df['status'] = df['status'].replace(to_replace = [df['color'] == 'green'], value = 'done')

但它什么也没做。

我也尝试过:df['status'] = df.where(cond = [df['color'] == 'green'] , other = 'done') 但这导致ValueError: Array conditional must be same shape as self 我不明白的错误。

如何正确替换我想要的内容?

最佳答案

进行批量更新的一种简单方法是使用 df.loc

df.loc[df.color == 'green', 'status'] = 'done'

color status
0 red not done
1 red not done
2 green done

关于python - 如何通过使用条件查找和替换数据框中的值来更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59275059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com