Python:按一列中的值搜索另一列中包含#号之间的值时出现KeyError

问题描述 投票:0回答:1

我正在尝试查找一列 (Column_A) 中的值是否包含在另一列 (Column_B) 中,该列的值由 # 符号分隔。然后我想在新列(Column_C)中返回匹配值。

数据如下所示:

我试过这个:

def find_matching_value(row):
    a_values=[float(x) for x in row[my_df1.Column_B].split('#') if x !='']
    if row[my_df1.Column_A] in a_values:
        return row['Column_A']
    else:
        return None

my_df2['Column_C']=my_df1.apply(find_matching_value, axis=1)

但是,我得到一个关键错误:

KeyError: "None of [Index(['#16.990000#16.990000#16.990000#28.990000#28.990000#16.99#16.99#16.99#21.99#21.99#21.99,\n'#13.490000#13.490000#13.990000#11.99#11.99#12.49', \n'#13.490000#13.390000#14.490000#16.990000#16.990000#17.490000#12.49#12.49#12.99#15.99#15.99#15.99'dtype='object', length=3)] are in the [index]"

不确定是什么导致了这里的问题。

python split keyerror
1个回答
0
投票

这里不需要使用

apply
,你可以稍微调整一下你的listcomp :

my_df1["Column_C"] = [a if any([b == str(a) for b in lst]) else None
                      for a, lst in zip(my_df1["Column_A"],
                                        my_df1["Column_B"].str.split("#"))]  

输出:

print(my_df1)
​
   Column_A                                                                                Column_B Column_C
0     16.99  #16.990000#16.990000#16.990000#28.990000#28.990000#16.99#16.99#16.99#21.99#21.99#21.99    16.99
1     11.99                                                    #13.49#13.49#13.99#11.99#11.99#12.49    11.99
2     12.49                #13.49#13.39#14.49#16.99#16.99#17.49#12.49#12.49#12.99#15.99#15.99#15.99    12.49
© www.soinside.com 2019 - 2024. All rights reserved.