python - 使用 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())
请建议。
解决方案
推荐阅读
- vb.net - VB:动态创建文件 - 然后写入文件
- sql - SYSDATE - 检索最近 2 分钟订单的时间戳
- javascript - 如何从另一个页面链接到 jQuery 过滤视图并选择默认过滤器?
- php - 在 php 上下载时重命名 zip 中的文件
- java - 即使有偏差,感知器也找不到正确的线(处理)
- sql - 如何在 teradata 中实现延迟功能。
- google-cloud-platform - 在构建触发器上使用 base64 编码值时,cloudbuil.yaml 不会解组
- mysql - Kubernetes Docker/MySQL 一个服务中的多个数据库
- css - 背景颜色在带有引导 col 类的 div 内可见
- google-tag-manager - 我无法使用 Google 跟踪代码管理器,dataLayer 推送未反映分析事件面板上的任何内容