You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Pandas DataFrame复制PDF到指定文件夹?求助解决ValueError

问题原因

你遇到的ValueError: 真值不明确,是因为直接在if条件里使用了Pandas的整个布尔Series(比如type == 'CBWOP')。Pandas无法判断你要基于整个Series的什么逻辑来返回单一真值(比如是所有元素都为True?还是至少一个为True?),因此抛出这个错误。

修正方案

需要遍历DataFrame的每一行数据,针对每行的单个值做判断和路径拼接,同时修复代码里的语法错误:

完整修正代码

import pandas as pd
import shutil
import os

# 读取数据
df = pd.read_excel(r'\\KCOW00\Jobs\72046\Design\Bridges\Statewide Bridge Data\z_Scratch\CCD\Python Tests\data.xlsx')

# 定义路径常量
src = r'\\KCOW00\Jobs\72046\Design\Bridges\Statewide Bridge Data'
yr8 = r'\2022_Year 8'
auto = r'\Field Investigation Reference\Automation'

culv = r'\KLBRP - CBWOP Field Sketch Forms - Culvert.pdf'
grdr = r'\KLBRP - CBWOP Field Sketch Forms - Girder Bridge.pdf'
slab = r'\KLBRP - CBWOP Field Sketch Forms - Slab Bridge.pdf'

def process_row(row):
    # 只处理Type为CBWOP的行
    if row['Type'] != 'CBWOP':
        return
    
    # 拼接目标文件夹路径
    target_dir = os.path.join(src, yr8.strip('\\'), row['District'], row['County'], row['Owner Group'], row['NBI Bridge Number'], 'Field Investigation')
    # 确保目标文件夹存在,不存在则创建
    os.makedirs(target_dir, exist_ok=True)
    
    # 根据BR_Type选择对应PDF文件
    if row['BR_Type'] == '19-Culvert':
        src_file = os.path.join(src, auto.strip('\\'), culv.strip('\\'))
        target_file = os.path.join(target_dir, culv.strip('\\'))
        shutil.copy2(src_file, target_file)
    elif row['BR_Type'] == '01-Slab':
        src_file = os.path.join(src, auto.strip('\\'), slab.strip('\\'))
        target_file = os.path.join(target_dir, slab.strip('\\'))
        shutil.copy2(src_file, target_file)
    elif row['BR_Type'] == '02-Stringer/Girder':
        src_file = os.path.join(src, auto.strip('\\'), grdr.strip('\\'))
        target_file = os.path.join(target_dir, grdr.strip('\\'))
        shutil.copy2(src_file, target_file)

# 遍历DataFrame的每一行执行处理
df.apply(process_row, axis=1)

关键改动说明

  • 修复函数定义语法:原def Add_Forms:缺少括号,改为接收每行数据的process_row(row)函数。
  • 使用df.apply(process_row, axis=1)遍历每行,确保每次处理的是单个行的数值,而非整个Series。
  • 用os.path.join()拼接路径,避免手动拼接\\导致的路径错误,同时自动处理不同系统的路径分隔符。
  • 添加os.makedirs(target_dir, exist_ok=True),确保目标文件夹存在,避免复制时因路径不存在报错。
  • 先判断Type是否为CBWOP,减少后续不必要的分支判断。

内容的提问来源于stack exchange,提问作者Duffalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:07:37