代码之家  ›  专栏  ›  技术社区  ›  kms

对数据帧应用一个函数,条件是检查'nan'`

  •  -1
  • kms  · 技术社区  · 4 年前

    我有 Null NaNs 在其中一个DataFrame列中。我想 apply 有条件检查 NaN 并将函数返回的值存储到新列中。

    import pandas as pd
    from numpy import NaN
    
    df = pd.DataFrame({'Col1': [1, 9, NaN],
                       'Col2': [1, 3, 5]}) 
    
    def sample_func(v1, v2, token):    
        # call API 
        r = cl_apicall(v1, v2, token)
        return r
    
    # mock api call
    def cl_apicall(v1, v2, token):
        return f"{v1},-{v2}-{token}"
    
    # Apply function
    df['new_col'] = df.apply(lambda x: sample_func(x['Col1'], x['Col2'], 'xxxxxx'), axis = 1)
    
    print(df)
    

       Col1  Col2          new_col
    0   1.0     1  1.0,-1.0-xxxxxx
    1   9.0     3  9.0,-3.0-xxxxxx
    2   NaN     5  nan,-5.0-xxxxxx
    

    我怎么写这封信 申请 南斯 无效的 col1 只有价值观?注:为了再现性,简化了功能。

    预期结果:

     Col1  Col2          new_col
    0   1.0     1  
    1   9.0     3  
    2   NaN     5  nan,-5.0-xxxxxx
    

    i、 仅e .apply Col1

    1 回复  |  直到 4 年前
        1
  •  2
  •   tdelaney    4 年前

    您可以先筛选所需的行,应用函数,然后分配给新列。熊猫们将在缺失的行中填充 NaN . 这通常比为每行运行apply更有效。

    import pandas as pd
    from numpy import NaN
    
    df = pd.DataFrame({'Col1': [1, 9, NaN],
                       'Col2': [1, 3, 5]}) 
    
    def sample_func(v1, v2, token):
        # call API 
        r = cl_apicall(v1, v2, token)
        return r
    
    # mock api call
    def cl_apicall(v1, v2, token):
        return f"{v1},-{v2}-{token}"
    
    # Apply function
    #df['new_col'] = df.apply(lambda x: sample_func(x['Col1'], x['Col2'], 'xxxxxx'), axis = 1)
    df['new_col'] = df[df['Col1'].isnull()].apply(lambda x: sample_func(x['Col1'], x['Col2'], 'xxxxxx'), axis = 1)
    print(df)
    

    后果

       Col1  Col2          new_col
    0   1.0     1              NaN
    1   9.0     3              NaN
    2   NaN     5  nan,-5.0-xxxxxx