pandas 熊猫根据另一列替换值条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53598233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas replace values condition based on another column
提问by thor
I have a dataframe that looks like this:
我有一个看起来像这样的数据框:
col1 col2
Yes 23123
No 23423423
Yes 34234
No 13213
I want to replace values in col2 so that if 'Yes' in col1 then return blank and if 'No' return the initial value
我想替换 col2 中的值,以便如果 col1 中的“是”则返回空白,如果“否”返回初始值
I want to see this:
我想看这个:
col1 col2
Yes
No 23423423
Yes
No 13213
I have tried this but 'No' is returning None:
我试过这个,但“否”返回无:
def map_value(x):
if x in ['Yes']:
return ''
else:
return None
df['col2'] = df['col1'].apply(map_value)
回答by Yuca
there are many ways to go about this, one of them is
有很多方法可以解决这个问题,其中之一是
df.loc[df.col1 == 'Yes', 'col2'] = ''
Output:
输出:
col1 col2
Yes
No 23423423
Yes
No 13213
回答by RavinderSingh13
Created df
by copying sample data from OP's post and using following command:
创建df
由OP的帖子复制样本数据,并使用下面的命令:
df=pd.read_clipboard();
df
col1 col2
0 Yes 23123
1 No 23423423
2 Yes 34234
3 No 13213
Could you please try following.
你可以试试下面的。
m=df['col1']=='No'
df['col2']=df['col2'].where(m,'')
df
After running code output will be as follows:
运行后代码输出如下:
col1 col2
0 Yes
1 No 23423423
2 Yes
3 No 13213
回答by damiaaaan
You can use numpy for this
您可以为此使用 numpy
import pandas as pd
import numpy as np
d = {'col1': ['yes', 'no', 'yes', 'no'], 'col2': [23123,23423423,34234,13213]}
df = pd.DataFrame(data=d)
df['col2'] = np.where(df.col1 == 'yes', '', df.col2)
df