我正在使用方法.lookup()
在两个不同的数据框中,用法为df2.lookup(df1.index, df1.column)
(即与Pandas-使用其他列值作为列名选择列不同)。
考虑以下MWE:
# Parameter
lo = -5
hi = 5
n = 4
idx = range(n)
rep = 2
# DF 1
idx_1 = np.tile(idx, rep)
data_1 = np.random.randint(lo, hi, n*rep)
df_1 = pd.DataFrame(data_1, index=idx_1, columns=['column'])
# DF 2
idx_2 = idx
col_2 = range(lo, hi+1)
data_2 = np.random.rand(n, len(col_2))
df_2 = pd.DataFrame(data_2, index=idx_2, columns=col_2)
# Result
result = df_2.lookup(df_1.index, df_1.column)
在我看来,这非常方便易懂。Pandas告诉我:
FutureWarning: The 'lookup' method is deprecated and will beremoved in a future version.You can use DataFrame.melt and DataFrame.locas a substitute.
很遗憾,我不知道替代方法的工作原理。
一种直观但效率较低的解决方案是:
result = [df_2.loc[df_1.index[i], df_1.iloc[i, 0]] for i in range(n*rep)]
是否有一种易于实现的替代方法,通过内置函数替换上述任务中的df.lookup()
?