windowws
windowws

Reputation: 377

Creating new column with a custom function

I have a dataframe that looks like this

Name    Total
a       400
b       120
c       500
d       512
e       250

i have a function which takes 2 values and return me a value after some customisation, i want to create a column for each Name like below

Name    Total   a   b   c   d   e
a       400                 
b       120                 
c       500                 
d       512                 
e       250                 

and apply that function with inputs as values in total column corresponding to name column like a,a , a,b , a,c , a,d, a,e and correspondingly fill the values under that column. For example, in column a for Name a i need to send 400 and 400 as value to that function and i get the return value and i need to fill that in column a. For column b Name a i need to send 400 and 120 as the values to that function and get the value and fill in column b and so on. Is there a smart pandas way of achieving it?

Upvotes: 1

Views: 106

Answers (1)

r-beginners
r-beginners

Reputation: 35145

I'm not sure of the expected output, but are the following results correct?

df1 = df.set_index('name').stack().unstack(level=0)
df1.reset_index(inplace=True)
df = df.merge(df1, left_index=True, right_index=True, how='outer')
df.drop('index', axis=1, inplace=True)
df
    name    Total   a   b   c   d   e
0   a   400 400.0   120.0   500.0   512.0   250.0
1   b   120 NaN NaN NaN NaN NaN
2   c   500 NaN NaN NaN NaN NaN
3   d   512 NaN NaN NaN NaN NaN
4   e   250 NaN NaN NaN NaN NaN

user function:

df1 = pd.DataFrame(index=df.index, columns=df['name'].to_list())

def get_transform(x):
    df1.iat[0,x.name] = x[1]

df.apply(get_transform, axis=1)
df = df.merge(df1, left_index=True, right_index=True)
df

name    Total   a   b   c   d   e
0   a   400 400 120 500 512 250
1   b   120 NaN NaN NaN NaN NaN
2   c   500 NaN NaN NaN NaN NaN
3   d   512 NaN NaN NaN NaN NaN
4   e   250 NaN NaN NaN NaN NaN

Upvotes: 1

Related Questions