python以优雅的方式按条件进行行替换
我有以下问题: 例如,给定一个数据帧python以优雅的方式按条件进行行替换,python,pandas,Python,Pandas,我有以下问题: 例如,给定一个数据帧 import pandas as pd df = pd.DataFrame({'col1':[1,0,0,1],'col2':['B','B','A','A'],'col3':[1,2,3,4]}) 在其他一些工具中,我可以根据条件轻松创建一个新列,例如 如果df['col1']='0'&~df['col2'],则使用'col2'创建新列'col3'。否则为'col1' 另一个工具运行得非常快。到目前为止,我还没有在python中找到相应的表达式 1.)我
import pandas as pd
df = pd.DataFrame({'col1':[1,0,0,1],'col2':['B','B','A','A'],'col3':[1,2,3,4]})
在其他一些工具中,我可以根据条件轻松创建一个新列,例如
如果df['col1']='0'&~df['col2'],则使用'col2'创建新列'col3'。否则为'col1'
另一个工具运行得非常快。到目前为止,我还没有在python中找到相应的表达式
1.)我尝试了np.where,它遍历行,但不允许在与精确行对应的结果中使用动态值
2.)我已经试过了。应用(lambda…)看起来很慢
如果你能找到一个优雅的方法来解决这个问题,我会很高兴的。Thanx.我认为需要使用notnull
而不是倒置的isnull
(谢谢@jpp):
试试这个:
import numpy as np
df['new_col'] = np.where(df['col1'] == 0 & (~df['col2'].isnull()), df['col2'], df['col1'] )
np.where比pd.apply快:您可以使用
df.loc
:
df['col3'] = df['col1']
df.loc[(df['col1'] == 0 )& (~df['col2'].isnull()), 'col3'] = df['col2']
df['col3'] = df['col1']
df.loc[(df['col1'] == 0 )& (~df['col2'].isnull()), 'col3'] = df['col2']