gpt4 book ai didi

python - 是否可以根据对单个 pandas DataFrame 列的查询跨行进行多次更新

转载 作者:行者123 更新时间:2023-12-02 16:37:52 24 4
gpt4 key购买 nike

我想一次性更新国家名称的数据框

import pandas as pd
df = pd.DataFrame( {'countries': ['United States of America','United Kingdom','Republic of Korea','Netherlands']})
df

输出 1:

Output 1:

我想更新国家名称,但这样做似乎效率不高

df.loc[df['countries']=='United States of America' ,'countries'] = 'USA'
df.loc[df['countries']=='United Kingdom' ,'countries'] = 'UK'
df.loc[df['countries']=='Republic of Korea' ,'countries'] = 'South Korea'
df.loc[df['countries']=='Netherlands' ,'countries'] = 'Holland'

df

上面的工作给我这个输出:

Output 2:

理想情况下,我想用以下内容更新它:

df.loc[df['countries'] in ['United States of America','United Kingdom','Republic of Korea','Netherlands'] 
,'countries'] = ['USA','UK','South Korea','Holland']

但是,我遇到了这个错误,我无法通过尝试使用 .any() 函数或我迄今为止尝试过的任何其他方法来克服它。

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

如果您能帮助我们更有效地使用相应的列表更新多个有序的资格,我们将不胜感激。

最佳答案

使用带有pd.DataFrame.replace的字典:

dd = {'United States of America':'USA', 
'United Kingdom':'UK',
'Republic of Korea':'South Korea',
'Netherlands':'Holland'}

df.replace(dd)

输出:

     countries
0 USA
1 UK
2 South Korea
3 Holland

关于python - 是否可以根据对单个 pandas DataFrame 列的查询跨行进行多次更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62286514/

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