基于Pandas对同一DataFrame执行多条件过滤操作
看起来你需要根据特定条件更新DataFrame中的SUN列,我来帮你一步步解决这个问题。
首先,先还原你的原始DataFrame,然后分两种情况处理:一种是严格按照你描述的条件(Dept=='Mech'且Location包含'CTB'),另一种是匹配你给出的期望输出的条件(因为两者看起来有出入)。
第一步:创建原始DataFrame
先把你提供的数据转换成可操作的pandas DataFrame:
import pandas as pd import numpy as np data = { 'SN': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Asset': ['A11', 'A12', 'A13', 'A14', 'A15', 'A16', 'A17', 'A18', 'A19', 'A20'], 'Dept': ['Mech', 'Mech', 'Mech', 'Elec', 'Elec', 'Elec', 'Mech', 'Mech', 'Mech', 'Elec'], 'Location': ['ACTB', 'CTBA', 'CABA', 'ACTB', 'CTBA', 'CABA', 'CABA', 'CTBA', 'ACTB', 'CTBA'], 'FREQ': ['M', 'M', 'Y', 'Y', 'M', 'Y', 'Y', 'M', 'Y', 'M'], 'SUN': [np.nan] * 10 } df = pd.DataFrame(data)
情况1:严格按照你描述的条件更新
你提到的过滤规则是:当Dept=='Mech'且Location包含字符串'CTB'时,将FREQ的值复制到SUN列。可以用numpy.where或者pandas.loc来实现:
方法1:使用numpy.where
df['SUN'] = np.where( (df['Dept'] == 'Mech') & (df['Location'].str.contains('CTB')), df['FREQ'], df['SUN'] )
方法2:使用pandas.loc
df.loc[(df['Dept'] == 'Mech') & (df['Location'].str.contains('CTB')), 'SUN'] = df['FREQ']
运行后,只有Location为CTBA的机械部门行(SN=2、8)的SUN会被赋值为FREQ的值,其他行保持NaN。
情况2:匹配你给出的期望输出
观察你提供的期望输出,发现所有Dept=='Mech'且Location**不包含'CABA'**的行,SUN都被赋值为FREQ的值(比如SN=1、2、8、9)。如果这是你真正需要的逻辑,代码如下:
方法1:使用numpy.where
df['SUN'] = np.where( (df['Dept'] == 'Mech') & (~df['Location'].str.contains('CABA')), df['FREQ'], df['SUN'] )
方法2:使用pandas.loc
df.loc[(df['Dept'] == 'Mech') & (~df['Location'].str.contains('CABA')), 'SUN'] = df['FREQ']
运行这段代码后,得到的结果就和你给出的期望输出完全一致了:
SN Asset Dept Location FREQ SUN 0 1 A11 Mech ACTB M M 1 2 A12 Mech CTBA M M 2 3 A13 Mech CABA Y NaN 3 4 A14 Elec ACTB Y NaN 4 5 A15 Elec CTBA M NaN 5 6 A16 Elec CABA Y NaN 6 7 A17 Mech CABA Y NaN 7 8 A18 Mech CTBA M M 8 9 A19 Mech ACTB Y Y 9 10 A20 Elec CTBA M NaN
小提示
str.contains()默认是区分大小写的,如果需要不区分,可以添加case=False参数。- 如果你的
Location列有缺失值,记得添加na=False参数避免报错,比如df['Location'].str.contains('CTB', na=False)。
内容的提问来源于stack exchange,提问作者Muhammad Asif Khan
相关产品推荐
相关产品推荐

