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
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___
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'})