Python 替换数据帧中的值时出现问题?

Python 替换数据帧中的值时出现问题?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有以下数据帧: 在: 输出: 我想用id替换所有水果(例如01到nn)。为此,我尝试使用pandas replace函数: df['Fruits'] = df['Fruits'].replace(['pinneapple', 'apple', 'tomato', 'grapes', 'orange'],\ ['01', '02', '03', '04',

我有以下数据帧:

在:

输出:

我想用id替换所有水果(例如
01
nn
)。为此,我尝试使用pandas replace函数:

df['Fruits'] = df['Fruits'].replace(['pinneapple', 'apple', 'tomato', 'grapes', 'orange'],\
                                                                      ['01', '02', '03', '04', '05'])

然而,当我完成上面的任务时,我感兴趣的列没有做任何调整。因此,如何将每个单词替换为预定义的数字?

您可以在以下内容中使用参数
regex=True

对于
代码
,您还可以使用
列表理解

fruits = ['pinneapple', 'apple', 'tomato', 'grapes', 'orange']
codes = [str(i + 1).zfill(2) for i, c in enumerate(fruits)]
print (codes)
['01', '02', '03', '04', '05']

df['Fruits'] = df['Fruits'].replace(fruits,codes, regex=True)
print (df)

                 Fruits
0   this should be a 01
1  this should be an 02
2   this should be a 03
3      this should 3 04
4  this should be an 05
5  this should be an 01
6  this should be an 02

尝试使用以下方法重置该值:

df['Fruits'] =  pd.DataFrame()

然后再次分配新值

谢谢你的帮助,杰兹!
df['Fruits'] = df['Fruits'].replace(['pinneapple', 'apple', 'tomato', 'grapes', 'orange'],\
                                    ['01', '02', '03', '04', '05'], regex=True)
print (df)
                 Fruits
0   this should be a 01
1  this should be an 02
2   this should be a 03
3      this should 3 04
4  this should be an 05
5  this should be an 01
6  this should be an 02
fruits = ['pinneapple', 'apple', 'tomato', 'grapes', 'orange']
codes = [str(i + 1).zfill(2) for i, c in enumerate(fruits)]
print (codes)
['01', '02', '03', '04', '05']

df['Fruits'] = df['Fruits'].replace(fruits,codes, regex=True)
print (df)

                 Fruits
0   this should be a 01
1  this should be an 02
2   this should be a 03
3      this should 3 04
4  this should be an 05
5  this should be an 01
6  this should be an 02
df['Fruits'] =  pd.DataFrame()