简体   繁体   中英

Apply function to dataframe based on column with other dataframe based on index

I would like to perform some operation (eg x*apples^y ) on the values of column apples, based on their color. The corresponding values are in a seperate dataframe:

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'apples': [2, 1, 5, 6, 7], 'color': [1, 1, 1, 2, 2]})
df2 = pd.DataFrame({'x': [100, 200], 'y': [0.5, 0.3]}).set_index(np.array([1, 2]), 'color')

I am looking for the following result:

   apples        color
0  100*2^0.5      1
1  100*1^0.5      1
2  100*5^0.5      1
3  200*6^0.3      2
4  200*7^0.3      2

Use DataFrame.join with default left join first and then operate with appended columns:

df = df1.join(df2, on='color')
df['apples'] = df['x'] * df['apples'] ** df['y']
print (df)
       apples  color    x    y
0  141.421356      1  100  0.5
1  100.000000      1  100  0.5
2  223.606798      1  100  0.5
3  342.353972      2  200  0.3
4  358.557993      2  200  0.3

There is left join, so append to new column in df1 should working:

df = df1.join(df2, on='color')
df1['apples'] = df['x'] * df['apples'] ** df['y']
print (df1)
       apples  color
0  141.421356      1
1  100.000000      1
2  223.606798      1
3  342.353972      2
4  358.557993      2

Another idea is use double map :

df1['apples'] = df1['color'].map(df2['x']) * df1['apples'] ** df1['color'].map(df2['y'])
print (df1)
       apples  color
0  141.421356      1
1  100.000000      1
2  223.606798      1
3  342.353972      2
4  358.557993      2

I think you need pandas.merge -

temp = df1.merge(df2, left_on='color', right_index= True, how='left')
df1['apples'] = (temp['x']*(temp['apples'].pow(temp['y'])))

Output

       apples  color
0  141.421356      1
1  100.000000      1
2  223.606798      1
3  342.353972      2
4  358.557993      2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM