2017-07-27 44 views
0

如何根据字典更新数据框的列值?一起使用.loc和.replace()

例如,我有DF,看起来像: df = pd.DataFrame({'B' : [100,101,102,103],'E' : pd.Categorical(["test","train","test","train"]), 'F' : [128,300,1205,2000]})

Out[28]:

 B  E  F 
0 100 test 128 
1 101 train 300 
2 102 test 1205 
3 103 train 2000 

dict = {300:301, 2000:2001}

df.loc[df['B'].isin([101,103])].replace(dict)

Out[31]: 
    B  E  F 
1 101 train 301 
3 103 train 2001 

这GIV es正确的结果,但是在原地进行复制警告,我需要使用此逻辑更新原始数据框。

此外,做一个非常低效的groupby & apply组合作品,但显然不是最佳。

我该如何做到这一点?

回答

2

您可以将结果分配到数据帧的相同位置:

d = {300:301, 2000:2001} 
mask = df.B.isin([101, 103]) 
df.loc[mask] = df.loc[mask].replace(d) 

df 
#  B  E  F 
#0 100 test 128 
#1 101 train 301 
#2 102 test 1205 
#3 103 train 2001 

或者你可以使用update

df.update(df.loc[df.B.isin([101, 103])].replace(d)) 
+0

谢谢,我从来没有使用过'update'。另外,我刚刚意识到'replace'如何知道要采取行动?它从来没有明确说过.....它只适用于df中的每个值吗?如果是这样,是否有一种方法只适用于特定列以防万一? – guy

+0

您可以将列名添加到'loc'以进行子集化并仅替换那些列,例如'df.update(df.loc [mask,cols] .replace(d))'或'df.loc [mask,cols] = df.loc [mask,cols] .replace(d)'假设'cols'是列名列表,例如'cols = ['F']'。 – Psidom

+0

也谢谢你的解决方案将我的整数转换为浮点数,为什么? – guy