Skip to main content
 首页 » 编程设计

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

2025年02月15日9sharpest

我有以下数据框:

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