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

标签 python pandas

我有以下数据框:

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/

相关文章:

python - 如何使用seaborn相对于行绘制多个条形图?

python - 从 url 加载压缩 (.gz) .csv 文件时出现问题

python 自定义 JSON 编码器/解码器未按预期工作

python - css 在本地工作但在部署到 heroku flask 后失败

python - Pandas:使用 `df.loc` 从 datetime64 到 int 的类型转换

python - 使用 Python 的 HDF 文件中的数据丢失

python - 将嵌套的 python 字典转换为多索引 pandas 数据框

python - Sqlite:无法选择具有大整数 id 的行

python - Cron 运行 Python 脚本 : Permission Errors

python - 将日期时间列拆分为日期和时间 Python