Skip to main content
 首页 » 编程设计

python之我可以用数据框一次替换一些值吗

2025年05月04日14myhome

现在我必须这样做:

df = pd.DataFrame({'column': ['A', 'B', 'C', 'D', 'E', 'F', 'G', '-']}) 
df['column'] = df['column'].str.replace('A', 'cat').replace('B', 'rabit').replace('C', 'octpath').replace('D', 'spider').replace('E', 'mammoth').replace('F', 'snake').replace('G', 'starfish') 

但我认为这很长而且难以阅读。 你知道一个简单的解决方案吗?

请您参考如下方法:

这是另一种使用 pandas.Series.replace 的方法:

d = {'A':'cat','B':'rabit', 'C':'octpath','D':'spider','E':'mammoth','F':'snake','G':'starfish'} 
df['column'] = df['column'].replace(d) 

输出:

    column 
0       cat 
1     rabit 
2   octpath 
3    spider 
4   mammoth 
5     snake 
6  starfish 
7         -