python - 空列表条件
问题描述
我从读取 excel 文件的列中得到一个列表,我需要验证列是否在列表中,如果没有,则将其创建为空,但条件不起作用,我知道缺少“城市”这一事实所以我期待它被创建,但不是。
files = os.listdir(input_path)
files_xlsx = [f for f in files if f[-5:] == ".xlsx"]
df = pd.DataFrame()
for f in files_xlsx:
wb = load_workbook(input_path + "\\" + f, read_only=True)
if 'New Leads' in wb.sheetnames:
df = pd.read_excel(input_path + "\\" + f, sheet_name="New Leads")
colre = [col for col in df.columns if "Email" in col]
for eo in colre:
df.rename(columns={eo: eo.replace(' ','').replace('*','').replace('**','') for eo in colre}, inplace=True)
dtcol = [col for col in df.columns if "FIRST NAME" in col.upper()]
for ex in dtcol:
df.rename(columns={ex: "First Name"}, inplace=True)
dtcol = [col for col in df.columns if "LAST NAME" in col.upper()]
for ex in dtcol:
df.rename(columns={ex: "Last Name"}, inplace=True)
不工作的代码
dtcol = [col for col in df.columns if "CITY" in col.upper()]
for ex in dtcol:
if len(dtcol)==0:
df['City'] = NaN
else:
df.rename(columns={ex: "City"}, inplace=True)
不工作的代码结束
dtcol = [col for col in df.columns if "COMPANY NAME" in col.upper()]
for ex in dtcol:
df.rename(columns={ex: "*** Company"}, inplace=True)
if "SOURCE" in cols:
df['Email'].replace('', np.nan, inplace=True)
df.dropna(subset=['Email'], inplace=True)
if df.dtypes['SOURCE'] != 'float':
df.dropna(how = 'all')
df['File'] = f
if df.SOURCE.map(lambda x: len(x)).max() <= 10:
df = pd.merge(df, df_ac[["SOURCE", "Lead Source", "Lead Category"]], on="SOURCE", how='left')
del df['SOURCE']
df.rename(columns={"Lead Source": "SOURCE"}, inplace=True)
else:
df.rename(columns={"SOURCE": "Lead Source"}, inplace=True)
df = pd.merge(df, df_ac[["Lead Source", "Lead Category"]], on="Lead Source", how='left')
df.rename(columns={"Lead Source": "SOURCE"}, inplace=True)
df_xlsx = pd.concat([df, df_xlsx], ignore_index=True)
else:
df_ns = df_ns.append([f], ignore_index=True)
else:
df_ns = df_ns.append([f], ignore_index=True)
else:
df_ns = df_ns.append([f], ignore_index=True)
解决方案
当你让 Python 遍历一个空列表时,它什么也不做,因为没有什么可以遍历的。所以放在if len(dtol)==0
for循环里面什么都不做;如果列表为空,则永远不会对其进行评估,如果列表不为空,则将其评估为 false (这很浪费,因为必须在循环的每次迭代中对其进行评估,即使每次都相同)。你需要把它放在外面。
dtcol = [col for col in df.columns if "CITY" in col.upper()]
if dtcol:
for ex in dtcol:
df.rename(columns={ex: "City"}, inplace=True)
else:
df['City'] = NaN
推荐阅读
- c++ - 比较 c 字符串和 c++ 字符串会产生分段错误吗?
- nlp - SideEffect 和 Condition 有什么区别?如何弄清楚?
- java - 应用程序无法在 IntelliJ 中启动 - NoSuchBeanDefinition importRegistry
- c# - 将字典绑定到数据网格的列
- sql - 在 SQL Server 中使用内部联接时如何排除不相关的数据?
- javascript - 过滤和排序嵌套的对象数组
- python - Panda 按特定列的总和分组并保留其他列
- python - 计算在特定点的方向上移动一个像素
- python - CheckBoxGroup 散景 Python
- numpy - 使用 colab reutrns 进行 VGG16 训练 WARNING:root:kernel