如何使用python仅在特定条件下执行脚本

2024-09-27 00:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在编写一个脚本,其中为各个列执行清理脚本

我必须处理那些脚本,如果它经历了一个特定的条件

例如

if flag = 'Not feasible':
    "Process the remaining steps"

输入数据:

name   age   Contact    col4   col5  col6  flag

NKJ    48!   96754789   8886H  AHBZ        Not feasible
Tom    27    98468300   ^686H  ANKZ        feasible
Mike   28@   78915359   3256H  AK9Z        Not feasible
NKJ    48!   96754789   8886H  AHBZ        Not feasible

JKN8    35   96451188   3566H  NK4Z        Not feasible

我只希望在flag=不可行时处理所有清理脚本

我正在尝试使用的脚本:

if flag == 'Not feasible':
  df['age'] = df['age'].replace('[^\d.]', '', regex=True).astype(float)
  df[['col4','col5']] = df[['col4','col5']].apply(lambda x: x.astype(str).str.replace('\W',''))
  df['contact'] = df['contact'].replace('[^\d.]', '', regex=True).astype(float)

像这样,我们还有几行正在执行,但不知道只有当flag==不可行时如何执行

使用上述条件时,得到错误:ValueError:序列的真值是不明确的。使用a.empty、a.bool()、a.item()、a.any()或a.all()。

请建议


Tags: 脚本dfageifnot条件replaceregex
2条回答

为了节省修改大量脚本以清理各个列的工作量,请按以下步骤执行:

  1. 首先将不需要处理的数据提取到另一个数据帧中
  2. 使用提取的行重新定义df,以便使用副本进行处理
  3. 使用原始语法运行清理脚本
  4. 使用.sort_index()将那些不用于处理行(从步骤1)的返回到已清理的结果(从步骤3)以恢复其原始顺序

df1 = df.loc[df['flag'] != 'Not feasible']               # Step 1
df = df.loc[df['flag'] == 'Not feasible'].copy()         # Step 2

# Run your cleaning codes with original syntax           # Step 3
df['age'] = df['age'].replace('[^\d.]', '', regex=True).astype(float)
df[['col4','col5']] = df[['col4','col5']].apply(lambda x: x.astype(str).str.replace('\W',''))
df['Contact'] = df['Contact'].replace('[^\d.]', '', regex=True).astype(float)

df = pd.concat([df, df1]).sort_index()                   # Step 4

结果:

print(df)


   name   age     Contact   col4  col5 col6          flag
0   NKJ  48.0  96754789.0  8886H  AHBZ       Not feasible
1   Tom    27  98468300.0  ^686H  ANKZ           feasible
2  Mike  28.0  78915359.0  3256H  AK9Z       Not feasible
3   NKJ  48.0  96754789.0  8886H  AHBZ       Not feasible
4  JKN8  35.0  96451188.0  3566H  NK4Z       Not feasible

未处理的数据合并回已清理的数据。在pd.concat()之后用.sort_index()保持原始行序列

您是否尝试使用布尔掩码进行筛选? 例如df.loc[df["flag"]=="Not feasible", 'age'] = df.loc[df["flag"]=="Not feasible", 'age'].replace('[^\d.]', '', regex=True).astype(float) 类似地,对于希望应用于df的所有其他转换

相关问题 更多 >

    热门问题