首页 > 解决方案 > 使用 Python 在条件语句中执行脚本

问题描述

如果满足特定条件,我一直在尝试执行其余的清理脚本。实际上有一个输入 Excel 数据集,其中数据在相等的时间间隔后不断添加。如果列标志=“不可行”,我只想处理脚本的其余部分,否则将保持数据原样。

最后我想显示当时的所有数据(一个通过脚本处理)+(不通过脚本处理)

输入数据 :

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
Adam   18#   78915899   3256H  AK7Z        Not feasible
Steve  23@   7891HI59   3256H  AK5Z        feasible
JKN8    35   96451188   3566H  NK4Z        Not feasible

预期输出数据:

name   age   Contact    col4   col5  col6  flag

NKJ    48    96754789   8886H  AHBZ        feasible
Tom    27    98468300   ^686H   ANKZ        feasible
Mike   28    78915359   3256H  AK9Z        feasible
NKJ    48    96754789   8886H  AHBZ        feasible
Adam   18    78915899   3256H  AK7Z        feasible
Steve  23@    7891HI59   3256H  AK5Z        feasible
JKN8   35    96451188   3566H  NK4Z        feasible

我之前尝试过的脚本:

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)
  df['flag'] = "feasible"

将脚本修改为:

df1 = df.loc[df['flag'] != 'Not feasible']      
df = df.loc[df['flag'] == 'Not feasible'].copy()

# Run your cleaning codes with original syntax   

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['flag'] = "feasible"

df = pd.concat([df, df1]).sort_index() 
print(df.head())

请建议。

标签: pythonpandas

解决方案


推荐阅读