我的例子是虚构的。我想用 apply() 和 lambda 来解决这个问题,尽管我也尝试过 iterrows() 但没有运气。我正在尝试向 df2 添加一列,该列根据每个 df2 行中的“项目”组合在 df1 中查找值。预先感谢您的帮助。
import pandas as pd
import numpy as np
import random
names= ['A', 'B', 'C', 'D', 'E']
df1 = pd.DataFrame( np.arange(25).reshape(5,5), columns = names, index = names)
n=5
data = {'Item 1' : random.sample(names, n),
'Item 2' : random.sample(names, n)}
df2 = pd.DataFrame(data)
#I can't get this to work.
df2['New'] = df2.apply(lambda x: df1.loc[df2.loc[x, 'Item 1'], df2.loc[x, 'Item 2']], axis=1)
#Since this works, I assume my error with apply and lambda. Thanks.
x=2
df1.loc[df2.loc[x, 'Item 1'], df2.loc[x, 'Item 2']]
答案 0 :(得分:1)
我一般会避免使用 apply
,特别是在 lambda 函数中使用 loc
调用。随着时间的推移,这会变得非常缓慢。
改用 numpy
的矢量化:
r = df2['Item 1'].map(dict(zip(df1.index, np.arange(len(df1.index)))))
c = df2['Item 2'].map(dict(zip(df1.columns, np.arange(len(df1.columns)))))
df2['new'] = df1.to_numpy()[r, c]
答案 1 :(得分:0)
df2['new'] = df2.apply(lambda x: df1.loc[x['Item 1'],x['Item 2']], axis=1)
输出:
>>> df2
Item 1 Item 2 new
0 D A 15
1 B B 6
2 A D 3
3 E C 22
4 C E 14
这是你想要的吗?如果不是,请添加您想查看的示例输出。