Let say I have a series s
index_column size
A 1
B 2
C 3
D 4
I want to add a new column contains a function f
def f(index_column):
% do something
return string
so that
index_column size function(index_column)
A 1 f(A)
B 2 f(B)
C 3 f(C)
D 4 f(D)
is it possible in Series
or do I need to do that in Dataframe
?
Here is one way to do it with a DataFrame:
import pandas as pd
def app_Z(s):
"""Append 'Z' onto column data"""
return s+'Z'
# recreate the series
s = pd.Series(data=[1,2,3,4], index=['A','B','C','D'], name='Size')
# create DataFrame and apply function to column 'Index'
df = pd.DataFrame(s)
df.reset_index(inplace=True)
df.columns = ['Index', 'Size']
df['Func'] = df['Index'].apply(app_Z)
df.set_index('Index', drop=True, inplace=True)
print(df)
Size Func
Index
A 1 AZ
B 2 BZ
C 3 CZ
D 4 DZ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With