是否可以使用np.where一次维护多个列? 通常,一列用np.where维护,所以我的编码看起来像这样:
df['col1] = np.where(df[df.condition == 'yes'],'sth', '')
df['col2'] = np.where(df[df.condition == 'yes'], 50.00, 0.0)
但是由于我两次测试相同条件的事实,我想知道,如果我可以通过2列并在一次运行中填充它们。
我试过了:
df['col1','col2'] = np.where(df[df.condition == 'yes'],['sth',50.00], ['',0.0])
但它不起作用。有没有办法实现这个目标?
谢谢:)
答案 0 :(得分:2)
我认为需要将布尔掩码重新整形为(N x 1)
:
m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))
只有解决问题的方法是list
s中的不同类型的值 - string
s的数字 - 然后numpy.where
两个输出列都转换为string
s。
<强>示例强>:
df = pd.DataFrame({'A':list('abcdef'),
'condition':['yes'] * 3 + ['no'] * 3})
print (df)
A condition
0 a yes
1 b yes
2 c yes
3 d no
4 e no
5 f no
m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))
print (df)
A condition col1 col2
0 a yes sth 50.0
1 b yes sth 50.0
2 c yes sth 50.0
3 d no 0.0
4 e no 0.0
5 f no 0.0
print (df.applymap(type))
A condition col1 col2
0 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
1 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
2 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
3 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
4 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
5 <class 'str'> <class 'str'> <class 'str'> <class 'str'>
编辑:我用NaN
的值测试它:
df = pd.DataFrame({'A':list('abcdefghi'),
'condition':['yes'] * 3 + ['no'] * 3 + [np.nan] * 3})
m = df.condition == 'yes'
df[['col1','col2']] = pd.DataFrame(np.where(m[:, None], ['sth',50.00], ['',0.0]))
print (df)
A condition col1 col2
0 a yes sth 50.0
1 b yes sth 50.0
2 c yes sth 50.0
3 d no 0.0
4 e no 0.0
5 f no 0.0
6 g NaN 0.0
7 h NaN 0.0
8 i NaN 0.0