![](/img/trans.png)
[英]Create new dense column in Pandas Dataframe by joining together two sparse columns
[英]Join together two sparse columns within a Pandas Dataframe
我有一个包含3列的数据框-ID,Match,Match2,我正在寻找创建名为Matchfinal的第三列。 我需要一个使用numpy的函数,该函数查看Match列并查看是否存在True或False。 如果为True,则在Matchfinal列中显示True。 如果为假,则转到Match2列,查看其中是否有True。 如果Match 2的值为True,则它将在Matchfinal列中写入True。 如果在Match和Match2列中都看到了False,则它将在Matchfinal列中写入False。
Example of dataframe:
ID Match Match 2 Matchfinal
123 True False True
1234 False True True
145 False False False
158 False True True
The code i am currently using just writes whatever I have in the column Match.
df['Matchfinal']= df.Match.combine_first(df['Match2'])
尝试:
df['Matchfinal'] = np.where((df['Match']|df['Match 2']), True, False)
这是适用于各种Match*
列的通用解决方案:
In [51]: x
Out[51]:
ID Match Match2 Match3 Match4
0 123 True False True True
1 1234 False True False True
2 145 False False False False
3 158 False True False False
In [52]: x['Matchfinal'] = x.filter(like='Match').any(1)
In [53]: x
Out[53]:
ID Match Match2 Match3 Match4 Matchfinal
0 123 True False True True True
1 1234 False True False True True
2 145 False False False False False
3 158 False True False False True
df["MatchFinal"] = df.apply(lambda x: any(x), axis=1)
这将是我的首选方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.