1

I have a similar problem like this, but this answer couldn't solve my problem Pandas: create two new columns in a dataframe with values calculated from a pre-existing column . I have a function which takes two parameters and return two different values in float Original dataframes are also in float

def FunctionName (a, b):
   some calculations---
   return x, y

I have df and I want to use function FunctionName so that I will have two new Series from those existing Series df['A], df['B]

df['A], df['B]
df['A_new'], df['B_new'] = df[['A'], df['B']].apply(FunctionName)

gives me an error

TypeError: unhashable type: 'list'

I also tried df['A_new'], df['B_new'] = FunctionName ( df['A'], df['B']) gives me an error

TypeError: cannot convert the series to <class 'float'>

I want to use return X values to df['A_new'] and Y values to df['B_new']

Can someone please tell, what i am missing here ?

user96564
  • 1,578
  • 5
  • 24
  • 42

1 Answers1

3

I believe need parameter axis=1 to apply for processes by rows with lambda function for define columns bynames and return Series for new columns - added by join:

df = pd.DataFrame({'A':[4,5,4,5,5,4],
                   'B':[7,8,9,4,2,3],
                   'C':[1,3,5,7,1,0]})

print (df)
   A  B  C
0  4  7  1
1  5  8  3
2  4  9  5
3  5  4  7
4  5  2  1
5  4  3  0

def FunctionName (a, b):
   x = a * 5
   y = b * 7
   return pd.Series([x, y], index=['A_new','B_new'])

df = df.join(df.apply(lambda x: FunctionName(x['A'], x['B']), axis=1))
print (df)
   A  B  C  A_new  B_new
0  4  7  1     20     49
1  5  8  3     25     56
2  4  9  5     20     63
3  5  4  7     25     28
4  5  2  1     25     14
5  4  3  0     20     21

def FunctionName (a, b):
   x = a * 5
   y = b * 7
   return pd.Series([x, y])

df[['A_new', 'B_new']] = df.apply(lambda x: FunctionName(x['A'], x['B']), axis=1)
print (df)
   A  B  C  A_new  B_new
0  4  7  1     20     49
1  5  8  3     25     56
2  4  9  5     20     63
3  5  4  7     25     28
4  5  2  1     25     14
5  4  3  0     20     21
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252