我有一个像下面这样的Pandas DataFrame:
col1 col2 col3
1 0.2 0.3 0.3
2 0.2 0.3 0.3
3 0 0.4 0.4
4 0 0 0.3
5 0 0 0
6 0.1 0.4 0.4
我想要将col1值替换为第二列(col2)中的值,仅当col1值等于0时,并且(对于剩余的零值)之后,再次使用第三列(col3)进行替换.期望的结果是下一个:
col1 col2 col3
1 0.2 0.3 0.3
2 0.2 0.3 0.3
3 0.4 0.4 0.4
4 0.3 0 0.3
5 0 0 0
6 0.1 0.4 0.4
我使用pd.replace函数做到了,但它似乎太慢了……我认为必须是一种更快的方法来实现它.
df.col1.replace(0,df.col2,inplace=True)
df.col1.replace(0,df.col3,inplace=True)
有更快的方法吗?使用其他函数而不是pd.replace函数?
解决方法:
使用np.where更快.使用与替换时使用的类似模式:
df['col1'] = np.where(df['col1'] == 0, df['col2'], df['col1'])
df['col1'] = np.where(df['col1'] == 0, df['col3'], df['col1'])
但是,使用嵌套的np.whe