简体   繁体   English

根据其他列中的条件替换pandas列中的某些特定值

[英]Replace some specific values in pandas column based on conditions in other column

This is my first question on StackOverflow, so let me know if I should formulate anything differently... 这是我关于StackOverflow的第一个问题,所以让我知道我是否应该以不同的方式制定...

I want to replace some values in a pandas Dataframe column, dependent on a condition related to values in another column, but leave the original values if the condition is False. 我想替换pandas Dataframe列中的某些值,这取决于与另一列中的值相关的条件,但如果条件为False则保留原始值。 For example: 例如:

import pandas as pd    
df=pd.DataFrame({'col1':['A','B','C','B'], 'col2':['z','x','x','x']},
                  columns=['col1','col2'])

df =
   col1 col2
0    A    z
1    B    x
2    C    x
3    B    x

Say, I want to replace the values in col2 to 'q' if the value in col1 is 'B' or 'C', but leave the original values ('z','x'), if the value in col1 is not B or C. In reality i have much larger DataFrame with hundreds of unique values in col1, and want to replace the values in col2 for about 20 of them. 比如说,如果col1中的值为'B'或'C',我想将col2中的值替换为'q',但如果col1中的值不是,则保留原始值('z','x') B或C.实际上,我有更大的DataFrame,在col1中有数百个唯一值,并希望将col2中的值替换为其中的大约20个。
My current solution is to create a dictionary, using col1 as keys and col2 as values, and then: 我目前的解决方案是创建一个字典,使用col1作为键,col2作为值,然后:

dict1.update({'B':'q'})
df[col2] = df[col1].map(dict1)

But this trick only works if values in the two columns correlate exactly (or if values in col1 are unique). 但是,只有当两列中的值完全相关(或者col1中的值是唯一的)时,此技巧才有效。

So i was wondering if there is a more elegant solution. 所以我想知道是否有更优雅的解决方案。 Thus only replace value in col2 if col1 matches a certain condition, else leave the original value. 因此,如果col1匹配某个条件,则只替换col2中的值,否则保留原始值。

mask the df first using loc and isin and call map as before: 首先使用locisin屏蔽df并像以前一样调用map

In [376]:
dict1 = {'B':'q'}
df.loc[df['col1'].isin(dict1.keys()), 'col2'] = df['col1'].map(dict1)
df

Out[376]:
  col1 col2
0    A    z
1    B    q
2    C    x
3    B    q

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM