【问题标题】:python pandas row wise substitution by condition in an elegant waypython pandas 以优雅的方式按条件逐行替换
【发布时间】:2018-09-24 19:20:01
【问题描述】:

我有以下问题:

例如,给定一个数据框,

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'].isnull() else 'col1' 则使用 'col2' 创建新列 'col3'

这个其他工具的工作速度非常快。目前在python中没有找到对应的表达式。

1.) 我尝试了 np.where 迭代行但不允许在结果中与确切行对应的动态值

2.) 我尝试过 .apply(lambda ... ),它似乎很慢。

如果您能找到解决此问题的优雅方法,我会很高兴。谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为需要numpy.wherenotnull 而不是倒置isnull(感谢@jpp):

    df = pd.DataFrame({'col1':[1,0,0,1],'col2':['B','B','A','A'],'col3':[1,2,3,4]})
    
    df['col3'] = np.where((df['col1'] == 0) & (df['col2'].notnull()), df['col2'], df['col1'])
    print (df)
       col1 col2 col3
    0     1    B    1
    1     0    B    B
    2     0    A    A
    3     1    A    1
    

    【讨论】:

      【解决方案2】:

      试试这个:

      import numpy as np
      df['new_col'] = np.where(df['col1'] == 0 & (~df['col2'].isnull()), df['col2'], df['col1'] )
      

      np.where 比 pd.apply 快:Why is np.where faster than pd.apply

      【讨论】:

        【解决方案3】:

        你可以使用df.loc:

        df['col3'] = df['col1']
        df.loc[(df['col1'] == 0 )& (~df['col2'].isnull()), 'col3'] = df['col2']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-07-02
          • 2020-06-12
          • 1970-01-01
          • 1970-01-01
          • 2018-06-27
          • 1970-01-01
          • 2022-12-20
          • 1970-01-01
          相关资源
          最近更新 更多