用途:
df = df.set_index('City')
df['dt.new'] = df.mask(df.apply(lambda x: x.str.contains('Non\s+'))).ffill(axis=1).iloc[:, -1]
为检查值选择列的替代解决方案:
cols = df.filter(regex='^dt\.').columns
#or use list of columns names
#cols = ['dt.t1','dt.t2','dt.t3']
df['dt.new'] = df[cols].mask(df[cols].apply(lambda x: x.str.contains('Non\s+'))).ffill(axis=1).iloc[:, -1]
print (df)
dt.t1 dt.t2 dt.t3 dt.new
City
NY US Non EU Non Asia US
Rome Non US EU Non Asia EU
SF US Non EU Non Asia US
HK Non US Non EU Asia Asia
详情:
首先set_index 到City 列,然后检查Non 字符串是否包含一个或多个空格:
df = df.set_index('City')
print (df.apply(lambda x: x.str.contains('Non\s+')))
dt.t1 dt.t2 dt.t3
City
NY False True True
Rome True False True
SF False True True
HK True True False
然后将匹配的值替换为NaNs 为mask:
print (df.mask(df.apply(lambda x: x.str.contains('Non\s+'))))
dt.t1 dt.t2 dt.t3
City
NY US NaN NaN
Rome NaN EU NaN
SF US NaN NaN
HK NaN NaN Asia
每行前向填充非缺失值:
print (df.mask(df.apply(lambda x: x.str.contains('Non\s+'))).ffill(axis=1))
dt.t1 dt.t2 dt.t3
City
NY US US US
Rome NaN EU EU
SF US US US
HK NaN NaN Asia
最后选择最后一列:
print (df.mask(df.apply(lambda x: x.str.contains('Non\s+'))).ffill(axis=1).iloc[:, -1])
City
NY US
Rome EU
SF US
HK Asia
Name: dt.t3, dtype: object
编辑:
m1 = df['dt.t1'] == 'US'
m2 = df['dt.t2'] == 'EU'
m3 = df['dt.t3'] == 'Asia'
df['dt.new'] = np.select([m1, m2, m3], ['US','EU','Asia'], default=None)
或者:
df['dt.new'] = np.where(m1, 'US',
np.where(m2, 'EU',
np.where(m3, 'Asia', None)))
print (df)
City dt.t1 dt.t2 dt.t3 dt.new
0 NY US Non EU Non Asia US
1 Rome Non US EU Non Asia EU
2 SF US Non EU Non Asia US
3 HK Non US Non EU Asia Asia