Ahsanul Haque Ahsanul Haque - 1 month ago 4
Python Question

How to form multiply column from a single pandas.apply() call ?

I have a function which returns a tuple of 4 items.

I have a DataFrame, what I want is to add 4 new column to my DataFrame by applying a function on one of the column. How to do it?

Below is my attempt:

a['w'], a['x'], a['y'], a['z'] =
a["existing"].apply(lambda x: find_data_from_ip(x))


But as this is a test DataFrame with only two row, I am getting the following error:


ValueError: need more than 2 values to unpack

Answer

You need return Series from function:

def find_data_from_ip(x):
    tup = (1,2,3,4)
    return (pd.Series(tup, index=['w','x','y','z']))

a = pd.DataFrame({'existing':[1,2,3]})
print (a)

a[['w','x','y','z']] = a["existing"].apply(lambda x: find_data_from_ip(x))
print (a)
   existing  w  x  y  z
0         1  1  2  3  4
1         2  1  2  3  4
2         3  1  2  3  4

Another solution is create DataFrame from column of tuples by from_records and then concat to original:

def find_data_from_ip(x):
    tup = (1,2,3,4)
    return (tup)

a = pd.DataFrame({'existing':[1,2,3]})
#print (a)

print (a["existing"].apply(lambda x: find_data_from_ip(x)))
0    (1, 2, 3, 4)
1    (1, 2, 3, 4)
2    (1, 2, 3, 4)
Name: existing, dtype: object

a1 = pd.DataFrame.from_records(a["existing"].apply(lambda x: find_data_from_ip(x))
                                            .values
                                            .tolist(),
                               columns = ['w','x','y','z'])
print (a1)
   w  x  y  z
0  1  2  3  4
1  1  2  3  4
2  1  2  3  4

print (pd.concat([a,a1],axis=1))
   existing  w  x  y  z
0         1  1  2  3  4
1         2  1  2  3  4
2         3  1  2  3  4
Comments