How To Use Functions With Pandas Dataframe
How can I use function with pandas dataframe. For example: a       | b london  | uk newyork | usa berlin  | germany  df1 = df[['a', 'b']]  def doSomething(df1):     return df1  doS
Solution 1:
You can use:
df = pd.DataFrame({'a':['london','newyork','berlin'],
                   'b':['uk','usa','germany'],
                   'c':[7,8,9]})
print (df)
df1 = df[['a', 'b']]
defdoSomething(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 dfprint (df1.apply(doSomething, axis=1))
0     london
1    newyork
2     berlin
dtype: objectIf need applymap it works with each element of df:
defdoSomething(x):
    return x + '___'#function works with elementprint (df1.applymap(doSomething))
            a           b
0   london___       uk___
1  newyork___      usa___
2   berlin___  germany___
Solution 2:
df1 = df[['a', 'b']]
def doSomething(df):
df2 = df['a']
return df2
df3 = df1.apply(doSomething, axis=1)
df3 = pd.DataFrame(df3).rename(columns={0: 'a'})
Post a Comment for "How To Use Functions With Pandas Dataframe"