使用Loop将数据帧中列中的每一行替换为它所显示的实例



我的数据帧中有一列名为"data"。我正在尝试将使用For循环的每个值替换为它出现的第一个实例的编号。例如

BatchID   ->   BatchID
Lot 11           1
Lot 11           1
Lot 11           1
Lot 11           1
Lot 12           2
Lot 12           2
Lot 13           3
Lot 14           4
Lot 14           4
Lot 14           4

这是我的代码:

unique_batches = ['Lot 11', 'Lot 12', 'Lot 13', 'Lot 14']
for i in range(len(data['BatchID'])):
for batch in unique_batches:
if data['BatchID'][i][:6] == batch:
data['BatchID'][i] = unique_batches.index(batch) + 1

这是我得到的错误:

TypeError: 'int' object is not subscriptable
---> 69         if data['BatchID'][i][:10] == batch:

此处不需要切片

batches = ['Lot 11', 'Lot 12', 'Lot 13', 'Lot 14']

这是经过精炼的代码

for i in range(len(df['BatchId'])):
for batch in batches:
if df["BatchId"][i]==batch:
df["BatchId"][i] = batches.index(batch)+1

您也可以使用替换函数。

以下是如何做到这一点的示例:

import pandas as pd
df = pd.DataFrame({'BatchID':['Lot 11','Lot 11','Lot 11','Think1','Lot 12',
'Lot 12','Lot 13','Lot 14','Lot 14','Lot 14']})

df = df.replace(r'Lot 1','',regex=True)
print(df)

结果如下:

请注意,其中一个值是Think1。因此,它没有被替换,因为它不符合模式。

BatchID
0       1
1       1
2       1
3  Think1
4       2
5       2
6       3
7       4
8       4
9       4

最新更新