[英]Pandas: Combine two string columns in dataframe by filling forward certain value
I have this df
: 我有这个
df
:
import pandas as pd
df1 = pd.DataFrame({
'Type': ['red', 'blue', 'red', 'red', 'blue'],
'V1': ['No', 'No', 'No', 'Yes', 'No'],
'V2': ['Yes', 'Yes', 'No', 'Yes', 'No'],
'V3': ['Yes', 'No', 'No', 'Yes', 'No'],
'V4': ['No', 'No', 'No', 'Yes', 'Yes']
})
And I want a dataframe that looks like this: 我想要一个看起来像这样的数据框:
Type V1 V2 V3 V4 V3_4
0 red No Yes Yes No Yes
1 blue No Yes No No No
2 red No No No No No
3 red Yes Yes Yes Yes Yes
4 blue No No No Yes Yes
So basically any "Yes" values from V3
are carried forward into a new column V3_4
as well as "Yes" values from V4
into column V3_4
. 因此,基本上,来自
V3
任何“是”值都将结转到新列V3_4
,也会将来自V4
“是”值V3_4
至列V3_4
。
It looks like I can do this either with a ffill or build a python function with some logic. 看起来我可以通过填充或使用某些逻辑构建python函数来执行此操作。 I would be fine with either method and am wondering what the most elegant is.
无论哪种方法都可以,我想知道最优雅的是什么。
df['V3_4'] = np.where(df.V3.eq('Yes') | df.V4.eq('Yes'), 'Yes', 'No')
Type V1 V2 V3 V4 V3_4
0 red No Yes Yes No Yes
1 blue No Yes No No No
2 red No No No No No
3 red Yes Yes Yes Yes Yes
4 blue No No No Yes Yes
Thanks to @Anton vBR, this can also be written a bit more concisely: 感谢@Anton vBR,这也可以写得更简洁一些:
np.where((df1[['V3','V4']].eq('Yes')).any(1), 'Yes', 'No')
Using np.where
使用
np.where
Ex: 例如:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'Type':['red','blue','red','red','blue'], 'V1':['No','No','No','Yes','No'], 'V2':['Yes','Yes','No','Yes','No'], 'V3':['Yes','No','No','Yes','No'], 'V4':['No','No','No','Yes','Yes']})
df1["V3_4"] = np.where(df1["V3"] == "No", df1["V4"], df1["V3"])
print(df1)
Output: 输出:
Type V1 V2 V3 V4 V3_4
0 red No Yes Yes No Yes
1 blue No Yes No No No
2 red No No No No No
3 red Yes Yes Yes Yes Yes
4 blue No No No Yes Yes
def build(a,b):
if a =='Yes':
return "Yes"
elif b =='Yes':
return "Yes"
else:
return "No"
df1['V3_4'] = df1[['V3','V4']].apply(lambda x : build(x),axis =1)
It may seems trivial but we can replace 'Yes' to True and perform or operation 看起来微不足道,但我们可以将“是”替换为True,然后执行或操作
df1 = pd.DataFrame({'Type':['red','blue','red','red','blue'], 'V1':['No','No','No','Yes','No'], 'V2':['Yes','Yes','No','Yes','No'], 'V3':['Yes','No','No','Yes','No'], 'V4':['No','No','No','Yes','Yes']})
df1[['V3','V4']]=df1[['V3','V4']].replace({'Yes':True,'No':False})
x=df1.V4.astype('bool')|df1.V3.astype('bool')
df1[['V3','V4']]=df1[['V3','V4']].replace({True:'Yes',False:'No'})
df1['V3_4']=x.replace({True:'Yes',False:'No'})
df1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.