[英]Multiple ifs for creating a new pandas column in dataframe
I have the following df dataframe in Pandas: 我在Pandas中有以下df数据帧:
index_1 index_2 index_3
85 91 104
73 25 112
48 97 15
22 85 101
I want to add a new column called SEGMENT to the previous dataframe, based on the values of the indexes, like this: 我想根据索引的值向前一个数据帧添加一个名为SEGMENT的新列,如下所示:
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"
Desired result is this: 期望的结果是这样的:
index_1 index_2 index_3 Segment
85 91 104 Medium high
73 25 112 High
48 97 15 None
22 85 101 High
How can I achieve this in Python with Pandas? 如何在Python中使用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. 我知道将每个条件作为一个单独的列放在一起很容易,但我需要在同一列中共同完成所有这些操作。
Thanks in advance! 提前致谢!
Use numpy.select
: 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.