用于在dataframe中创建新pandas列的多个ifs [英] Multiple ifs for creating a new pandas column in dataframe

查看:279
本文介绍了用于在dataframe中创建新pandas列的多个ifs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Pandas中有以下 df 数据框:

I have the following df dataframe in Pandas:

index_1    index_2    index_3
85         91         104
73         25         112
48         97         15
22         85         101

我想根据索引的值向前一个数据框添加一个名为 SEGMENT 的新列,如下所示:

I want to add a new column called SEGMENT to the previous dataframe, based on the values of the indexes, like this:

if ((df['index_1'] > 90) & (df['index_2'] > 90) & (df['index_3'] > 90)) 
then **SEGMENT** should be **All**

if ((df['index_1'] > 90) & (df['index_2'] > 90))
then **SEGMENT** should be **Medium**

if ((df['index_2'] > 90) & (df['index_3'] > 90))
then **SEGMENT** should be **Medium high**

if ((df['index_2'] > 90))
then **SEGMENT** should be **Medium low**

if ((df['index_3'] > 90))
then **SEGMENT** should be **High**

if none of the indexes are greater than 90, put "None"

所需结果为这个:

index_1    index_2    index_3    Segment
85         91         104        Medium high
73         25         112        High
48         97         15         None
22         85         101        High

我如何在Python中实现这一点熊猫?

How can I achieve this in Python with Pandas?

我知道将每个条件作为一个单独的列放在一起很容易,但我需要在同一列中将所有这些条件放在一起。

I know it is easy to do by putting each condition as a separate column, but I need all this together in the same column.

提前致谢!

推荐答案

使用 numpy.select

m1 = df['index_1'] > 90
m2 = df['index_2'] > 90
m3 = df['index_3'] > 90

m = [m1 & m2 & m3, m1 & m2, m2 & m3, m2, m3]
v = ['All','Medium','Medium high','Medium low','High']

df['Segment'] = np.select(m, v, default=None)
print (df)
   index_1  index_2  index_3      Segment
0       85       91      104  Medium high
1       73       25      112         High
2       48       97       15   Medium low
3       22       85      101         High

这篇关于用于在dataframe中创建新pandas列的多个ifs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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