How to use functions with pandas dataframe

后端 未结 2 1997
春和景丽
春和景丽 2021-01-25 15:41

How can I use function with pandas dataframe. For example:

a       | b
london  | uk
newyork | usa
berlin  | germany

df1 = df[[\'a\', \'b\']]

def doSomething(df         


        
2条回答
  •  有刺的猬
    2021-01-25 16:01

    You can use:

    df = pd.DataFrame({'a':['london','newyork','berlin'],
                       'b':['uk','usa','germany'],
                       'c':[7,8,9]})
    
    print (df)
    df1 = df[['a', 'b']]
    
    def doSomething(x):
        return x.a
    
    #function works with DataFrame 
    print (doSomething(df1))
    0     london
    1    newyork
    2     berlin
    Name: a, dtype: object
    
    #function works with Series, columns are transformed to index of Series
    #return for each row value of Series with index a which is transformed to column in output df
    print (df1.apply(doSomething, axis=1))
    0     london
    1    newyork
    2     berlin
    dtype: object
    

    If need applymap it works with each element of df:

    def doSomething(x):
        return x + '___'
    
    #function works with element
    print (df1.applymap(doSomething))
                a           b
    0   london___       uk___
    1  newyork___      usa___
    2   berlin___  germany___
    

提交回复
热议问题