gpt4 book ai didi

python - 将字典键值与多值索引进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:03 25 4
gpt4 key购买 nike

我想比较以下字典键:

{('F123', 1): 'R'}

到以下数据帧的索引 ('F123', 1):

Connector Pin   Connector   Pin          Adj.         Color        
F123 1 F123 1 [2, 6, 7] NaN

如果字典键等于数据帧索引 ('F123', 1),我想将字典值 ('R') 复制到与匹配索引关联的颜色列中。字典和数据框都有很多行,但为了解释起见,我只包含了每一行。速度并不重要,因为数据集不够大。

if(df.index == dict.key()):
df['Color'] = dict.value()

我在语法上苦苦思索如何解决这个问题。

更新:我在下面尝试了这个(我知道这是错误的)。仍在尝试确定如何测试所有 dict。一键一键,无需硬编码。

s = df.iterrows(pd.Series(dict.keys()))
df['Color'] = s

最佳答案

从字典中创建一个 Series,然后将 Color 列分配给它:

In [11]: df
Out[11]:
Connector Pin Connector.1 Pin.1 Adj. Color
F123 1 F123 1 [2, 6, 7] NaN

In [12]: s = pd.Series({('F123', 1): 'R'})

In [13]: df["Color"] = s

In [14]: df
Out[14]:
Connector Pin Connector.1 Pin.1 Adj. Color
F123 1 F123 1 [2, 6, 7] R

关于python - 将字典键值与多值索引进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54429709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com