gpt4 book ai didi

Python Pandas 使用基于具有重叠索引的另一个数据框中的列的值更新数据框列

转载 作者:行者123 更新时间:2023-11-28 22:14:13 25 4
gpt4 key购买 nike

这可能有一个简单的答案,但不知何故我没有看到它。

我有两个数据帧 df_adf_bdf_b.indexdf_a.index 的子集。

df_a

Actioncode Group

Mary 1.0 I
Paul 1.0 I
Robert 4.0 O
David 4.0 O
Julia 4.0 O

请注意,Group 属于 ActionCode(只是使 actioncode 可读。

df_b

Group

Paul O
Robert I

我想要的是 df_a Actioncode 如果名称在 df_b 中并且 Group 是 ' O' 和 df_a Actioncode 如果名称在 df_b 中并且 Group 是“I”,则显示 3.0。

所以结果是:

    df_a

Actioncode Group

Mary 1.0 I
Paul 5.0 I
Robert 3.0 O
David 4.0 O
Julia 4.0 O

我试过 where 但似乎无法获取它。

df_a['Actioncode'] =  df_a['Actioncode'].where(df_b['Group'] == 'O', 5.0)

但这不太对。

我可以迭代,但它不是 pythonic。

见解?

谢谢,

最佳答案

您可以使用 np.select为此,它的工作方式类似于 np.where 但具有多个条件/输出:

# Transform index of df_a to series for mapping
a_idx = df_a.index.to_series()

# Condition that df_a's index is in df_b
idx_in = a_idx.isin(df_b.index)

# map df_a's index to the df_b groups
mapped = a_idx.map(df_b.Group)

# apply np.select on your conditions:
conds = [(idx_in) & (mapped == 'O'),
(idx_in) & (mapped == 'I')]

choices = [5,3]


df_a['Actioncode'] = np.select(conds,choices, df_a.Actioncode)

>>> df_a
Actioncode Group
Mary 1.0 I
Paul 5.0 I
Robert 3.0 O
David 4.0 O
Julia 4.0 O

关于Python Pandas 使用基于具有重叠索引的另一个数据框中的列的值更新数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506957/

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