如何比较同一数据框的两列? [英] How to compare two columns of the same dataframe?

查看:106
本文介绍了如何比较同一数据框的两列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a dataframe like this:

 match_id inn1  bat  bowl  runs1 inn2   runs2   is_score_chased
    1     1     KKR  RCB    222  2      82          1
    2     1     CSK  KXIP   240  2      207         1
    8     1     CSK  MI     208  2      202         1
    9     1     DC   RR     214  2      217         1
   33     1     KKR  DC     204  2      181         1

现在,我想通过比较 runs1 runs2 中的值来更改 is_score_chased 列中的值.如果run1> runs2,则该行中的对应值应为是" ,否则应为. 我尝试了以下代码:

Now i want to change the values in is_score_chased column by comparing the values in runs1 and runs2 . If runs1>runs2, then the corresponding value in the row should be 'yes' else it should be no. I tried the following code:

for i in (high_scores1):
  if(high_scores1['runs1']>=high_scores1['runs2']):
      high_scores1['is_score_chased']='yes'
  else:
      high_scores1['is_score_chased']='no' 

但是没有用.如何更改列中的值?

But it didn't work. How do i change the values in the column?

推荐答案

您可以更轻松地使用

You can more easily use np.where.

high_scores1['is_score_chased'] = np.where(high_scores1['runs1']>=high_scores1['runs2'], 
                                           'yes', 'no')

通常,如果您发现自己试图像设置列那样进行显式迭代,则有一个类似于applywhere的抽象,它将更快,更简洁.

Typically, if you find yourself trying to iterate explicitly as you were to set a column, there is an abstraction like apply or where which will be both faster and more concise.

这篇关于如何比较同一数据框的两列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆