Skip to main content
 首页 » 编程设计

python之在遍历 pandas 数据框时更新列中的值

2024年11月24日9pengyingh

我正在编写一个脚本来从图像中提取一些细节。我正在尝试遍历具有我的图像名称的数据框。如何向数据框添加一个新列,以根据图像名称适本地填充提取的名称?

for image in df['images']: 
    concatenated_name                    = ''.join(name) 
    df.loc[image, df['images']]['names'] = concatenated_name 

预期:

Index images names 
0     img_01 TonyStark 
1     img_02 Thanos 
2     img_03 Thor 

得到:

Index images names 
0     img_01 Thor 
1     img_02 Thor 
2     img_03 Thor 

请您参考如下方法:

使用apply在每一行上应用一个函数:

def get_name(image): 
    # Code for getting the name 
    return name 
 
df['names'] = df['images'].apply(get_name) 

根据您添加了更多详细信息的回答,应该可以将其缩短为:

def get_details(filename): 
    image = os.getcwd() + filename 
    data = pytesseract.image_to_string(Image.open(image)) 
    . 
    . 
    .  
    data = ''.join(a)  
    return data 
 
df['data'] = df['filenames'].apply(get_details) 
# save df to csv / excel / other