我想根据其颜色对列苹果的值执行一些操作(例如x*apples^y
)。相应的值在单独的数据帧中:
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')
我正在寻找以下结果:
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
答案 0 :(得分:1)
首先将DataFrame.join
与默认的左联接一起使用,然后对附加的列进行操作:
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
有左联接,因此将附加到df1
中的新列应该可以正常工作
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
另一个想法是使用双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
答案 1 :(得分:0)
我认为您需要pandas.merge-
temp = df1.merge(df2, left_on='color', right_index= True, how='left')
df1['apples'] = (temp['x']*(temp['apples'].pow(temp['y'])))
输出
apples color
0 141.421356 1
1 100.000000 1
2 223.606798 1
3 342.353972 2
4 358.557993 2