热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python列替换_python–Pandas:根据来自另一列的匹配替换列值

我在第一个数据框df1[“ItemType”]中有一列,如下所示,Dataframe1ItemType1redTomatowhitePotatoyellowPotatogreenC

我在第一个数据框df1 [“ItemType”]中有一列,如下所示,

Dataframe1

ItemType1

redTomato

whitePotato

yellowPotato

greenCauliflower

yellowCauliflower

yelloSquash

redOnions

YellowOnions

WhiteOnions

yellowCabbage

GreenCabbage

我需要根据从另一个数据框创建的字典替换它.

Dataframe2

ItemType2 newType

whitePotato Potato

yellowPotato Potato

redTomato Tomato

yellowCabbage

GreenCabbage

yellowCauliflower yellowCauliflower

greenCauliflower greenCauliflower

YellowOnions Onions

WhiteOnions Onions

yelloSquash Squash

redOnions Onions

请注意,

>在dataframe2中,某些ItemType与ItemType中的相同

dataframe1.

> dataframe2中的某些ItemType具有nullCabbage等空值.

> dataframe2中的ItemType与dataframe中的ItemType无关

如果相应的Dataframe2 ItemType中的值匹配,我需要替换Dataframe1 ItemType列中的值,newType保持在bullet-points中列出的异常之上.

如果没有匹配,那么值必须是[无变化].

到目前为止,我得到了.

import pandas as pd

#read second `csv-file`

df2 = pd.read_csv('mappings.csv',names = ["ItemType","newType"])

#conver to dict

df2=df2.set_index('ItemType').T.to_dict('list')

下面给出的匹配替换不起作用.他们正在插入NaN值而不是实际值.这些是基于SO的讨论here.

df1.loc[df1['ItemType'].isin(df2['ItemType'])]=df2[['NewType']]

要么

df1['ItemType']=df2['ItemType'].map(df2)

提前致谢

编辑

两个数据框中的两个列标题具有不同的名称.因此,dataframe1列是ItemType1,第二个数据帧中的第一列是ItemType2.错过了第一次编辑.



推荐阅读
author-avatar
菜蔸蔸
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有