我一直在编写一个脚本,其中为各个列执行清理脚本
我必须处理那些脚本,如果它经历了一个特定的条件
例如
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()。
请建议
为了节省修改大量脚本以清理各个列的工作量,请按以下步骤执行:
df
,以便使用副本进行处理.sort_index()
将那些不用于处理行(从步骤1)的返回到已清理的结果(从步骤3)以恢复其原始顺序李>结果:
未处理的数据合并回已清理的数据。在
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的所有其他转换相关问题 更多 >
编程相关推荐