如果Pandas中的逻辑,Python 3 [英] If logic in Pandas, Python 3

查看:122
本文介绍了如果Pandas中的逻辑,Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas Dataframe,我想从中比较两列并根据比较结果创建一个新列。逻辑如下:

I've got a Pandas Dataframe from which I want to compare two columns and create a new column with a calculation based off the result of the comparison. Logic would be the following:

If df['column1']>df['column2'] :
   df['New column']=(df['column1']+df['column2'])
else :
   df['New column']=(df['column1']+df['column2']+1)

我对Pandas和Python相当新,所以我很确定我的结构错了。你们能指出我正确的方向吗?

I am fairly new to Pandas and Python so I'm sure I'm getting the structure wrong. Could you guys point me in the right direction?

推荐答案

我认为这应该是你的工作。虽然您可以在stackoverflow上找到类似的问题而无需启动新问题。无论如何。

I think this should do your work. Although you can find such similar question on stackoverflow without starting new question. Anyways.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB'))

def get_new_col_val(row):
    if row['A'] > row['B']:
        return row['A'] + row['B']
    else:
        return row['A'] + row['B'] + 1

df['new_col'] = df.apply(get_new_col_val, axis=1)

这是最简单的方法,但可以通过其他方式完成此任务。

This is the simplest approach but there can be other ways of getting this done.

享受!!!

这篇关于如果Pandas中的逻辑,Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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