Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas : Add new column with function based on index

Tags:

python

pandas

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 ?

like image 216
Mrye Avatar asked Dec 04 '15 04:12

Mrye


1 Answers

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
like image 185
Steve Misuta Avatar answered Oct 29 '22 02:10

Steve Misuta