DataFrame.lookup需要具有最新版本Pandas的唯一索引和列

问题描述

我正在使用python3.7,但我遇到的熊猫最新版本存在问题。 这是我的代码

import pandas as pd
import numpy as np

data = {'col_1':[9087.6000,9135.8000,np.nan,9102.1000],'col_2':[0.1648,0.1649,'',5.3379],'col_nan':[np.nan,np.nan],'col_name':['col_nan','col_1','col_2','col_nan']
        }
df = pd.DataFrame(data,index=[101,102,104])

col_lookup = 'results'
col_result = 'col_name'
df[col_lookup] = df.lookup(df.index,df[col_result])

代码在Pandas 1.0.3版中可以正常工作,但是 当我尝试使用1.1.1版时,会发生以下错误

“ ValueError:DataFrame.lookup需要唯一的索引和列”

数据框确实包含索引“ 102”的重复项。

出于不同的原因,我必须使用熊猫1.1.1版本。有没有使用“ lookup”命令的解决方案来支持此版本的熊猫的索引复制?

预先感谢您的帮助。

解决方法

放置唯一索引,然后恢复旧索引...

import pandas as pd
import numpy as np

data = {'col_1':[9087.6000,9135.8000,np.nan,9102.1000],'col_2':[0.1648,0.1649,'',5.3379],'col_nan':[np.nan,np.nan],'col_name':['col_nan','col_1','col_2','col_nan']
        }
df = pd.DataFrame(data,index=[101,102,104])

col_lookup = 'results'
col_result = 'col_name'
df.reset_index(inplace=True)
df[col_lookup] = df.lookup(df.index,df[col_result])
df = df.set_index(df["index"]).drop(columns="index")

,

非唯一索引是一个错误:Github link

熊猫1.1.1中的

“查找”方法不允许您传递非唯一索引作为输入参数。 在“ frame.py”中“ lookup”方法的开头添加了以下代码,对我来说(第3836行):

C:\ Users \ Sajad \ AppData \ Local \ Programs \ Python \ Python38 \ Lib \ site-packages \ pandas \ core \ frame.py

if not (self.index.is_unique and self.columns.is_unique):
# GH#33041
    raise ValueError("DataFrame.lookup requires unique index and columns")

但是,如果此错误处理程序不存在,则此方法中的以下过程将以for循环结尾。用内置的for循环替换最后一行,可以得到与以前的熊猫版本相同的结果。

result = np.empty(len(df.index),dtype="O")
for i,(r,c) in enumerate(zip(df.index,df[col_result])):
    result[i] = df._get_value(r,c)
df[col_lookup] = result