gpt4 book ai didi

python - 如何从 dataFrame 单元格中获取值以在另一个位置填充值?

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

我有以下数据框:

ID | Parent ID | Direction
1 | 0 | North
2 | 1 | South
3 | 1 | West
4 | 0 | East

我想编写一个函数,将所有具有非零“父 ID”的行的方向更改为相应父级的方向。

期望的结果:

ID | Parent ID | Direction
1 | 0 | North #Ignore because Parent Id = 0
2 | 1 | North #Changed to Direction of Parent Id = 1
3 | 1 | North #Changed to Direction of Parent Id = 1
4 | 0 | East #Ignore because Parent Id = 0

下面是创建上述示例数据帧的代码:

df = pd.DataFrame ({'ID' : [1,2,3,4],
'Parent ID' : [0,1,1,0],
'Direction' : ['North', 'South','West','East']})

我尝试编写一个函数并调用父 ID 上的映射,但我没有成功。

最佳答案

你可以试试这个:

to_replace = df['Parent ID'] != 0
df.loc[to_replace, 'Direction'] = df['Parent ID'][to_replace].map(df.set_index("ID").Direction)
df

enter image description here

关于python - 如何从 dataFrame 单元格中获取值以在另一个位置填充值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743167/

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