如何创建一个新的列,其中的值是基于现有列进行选择的?

495
如何将以下数据框添加一个名为color的列,使得当Set == 'Z'时,color='green',否则color='red'
   Type  Set
1     A    Z
2     B    Z           
3     B    X
4     C    Y

1
相关:在Pandas中根据其他列的值创建新列/逐行应用多列的函数(相同的思路,但选择条件基于多列) - undefined
13个回答

1041

如果你只有两个选择可供选择,那么请使用np.where

df['color'] = np.where(df['Set']=='Z', 'green', 'red')

例如,

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)

产量

  Set Type  color
0   Z    A  green
1   Z    B  green
2   X    B    red
3   Y    C    red

如果您有超过两个条件,请使用np.select例如,如果您想要color为:

  • yellow(df['Set'] == 'Z') & (df['Type'] == 'A')
  • 否则 blue(df['Set'] == 'Z') & (df['Type'] == 'B')
  • 否则 purple(df['Type'] == 'B')
  • 否则 black

那么请使用

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
conditions = [
    (df['Set'] == 'Z') & (df['Type'] == 'A'),
    (df['Set'] == 'Z') & (df['Type'] == 'B'),
    (df['Type'] == 'B')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)

产生的结果
  Set Type   color
0   Z    A  yellow
1   Z    B    blue
2   X    B  purple
3   Y    C   black

182

列表推导式是另一种有条件地创建新列的方法。如果您正在处理对象类型的列,就像在您的示例中一样,列表推导通常比大多数其他方法表现更好。

示例列表推导:

df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]

%timeit测试:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
%timeit df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit df['color'] = np.where(df['Set']=='Z', 'green', 'red')
%timeit df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')

1000 loops, best of 3: 239 µs per loop
1000 loops, best of 3: 523 µs per loop
1000 loops, best of 3: 263 µs per loop

17
需要注意的是,对于更大的数据框(例如 pd.DataFrame({'Type':list('ABBC')*100000, 'Set':list('ZZXY')*100000})),numpy.where 要比 map 更快,但列表推导式则表现最佳(约比 numpy.where 快50%)。 - blacksite
5
如果条件需要从多个列获取信息,是否可以使用列表推导式?我想要类似于这样的东西(以下代码无法正常运行):df['color'] = ['red' if (x['Set'] == 'Z') & (x['Type'] == 'B') else 'green' for x in df] - Matti
2
将iterrows添加到数据框中,然后您可以通过行访问多个列:['red' if (row['Set'] == 'Z') & (row['Type'] == 'B') else 'green' for index, row in in df.iterrows()] - cheekybastard
1
请注意,这种巧妙的解决方案无法处理需要从数据框中的另一个系列中获取替换值的情况,例如df['color_type'] = np.where(df['Set']=='Z', 'green', df['Type']) - Paul Rougieux
3
@cheekybastard 或者不要这样做,因为 .iterrows() 很慢,而且在迭代时不应修改 DataFrame。 - AMC
对我来说,df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']] 是有效的。 - PythonWizard

30
以下方法比此处计时的方法慢,但我们可以基于多列内容计算额外的列,并且可以为额外的列计算多于两个的值。
只使用“Set”列的简单示例:
def set_color(row):
    if row["Set"] == "Z":
        return "red"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

考虑更多颜色和更多列的示例:

def set_color(row):
    if row["Set"] == "Z":
        return "red"
    elif row["Type"] == "C":
        return "blue"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C   blue

编辑(2019年6月21日):使用plydata

还可以使用plydata来完成这种操作(尽管似乎比使用assignapply更慢)。

from plydata import define, if_else

简单的if_else

df = define(df, color=if_else('Set=="Z"', '"red"', '"green"'))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

嵌套的if_else语句:

df = define(df, color=if_else(
    'Set=="Z"',
    '"red"',
    if_else('Type=="C"', '"green"', '"blue"')))

print(df)                            
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B   blue
3   Y    C  green

28

另一种实现此目标的方式是

df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')

25

这里有另一种方法来解决这个问题,使用一个字典将新的值映射到列表中的键:

def map_values(row, values_dict):
    return values_dict[row]

values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})

df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))

它看起来是什么样子:

df
Out[2]: 
  INDICATOR  VALUE  NEW_VALUE
0         A     10          1
1         B      9          2
2         C      8          3
3         D      7          4

当您需要进行许多ifelse类型语句(即需要替换许多唯一值)时,这种方法可以非常强大。

当然,您也可以始终这样做:

df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)

但是在我的机器上,这种方法比上面的apply方法慢了三倍以上。

你也可以使用dict.get来达到同样的效果:

df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]

3
更新:在100,000,000行,52个字符串值上,.apply()需要47秒,而.map()仅需要5.91秒。 - AMC

25

你可以简单地使用强大的.loc方法,并根据需要使用一个或多个条件(在pandas=1.0.5中测试过)。

代码摘要:

df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))
df['Color'] = "red"
df.loc[(df['Set']=="Z"), 'Color'] = "green"

#practice!
df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"

解释:

df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))

# df so far: 
  Type Set  
0    A   Z 
1    B   Z 
2    B   X 
3    C   Y

添加一个名为“color”的列,并将所有值设置为“红色”

df['Color'] = "red"

应用您的单个条件:

df.loc[(df['Set']=="Z"), 'Color'] = "green"


# df: 
  Type Set  Color
0    A   Z  green
1    B   Z  green
2    B   X    red
3    C   Y    red

如果需要,您可以使用多个条件:

df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"

您可以在此处阅读有关Pandas逻辑运算符和条件选择的内容: Pandas中用于布尔索引的逻辑运算符


5

您可以使用Pandas方法wheremask

df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False

或者
df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True

或者,您可以使用带有Lambda函数的transform方法:

df['color'] = df['Set'].transform(lambda x: 'green' if x == 'Z' else 'red')

输出:

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

@chai的性能比较:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC')*1000000, 'Set':list('ZZXY')*1000000})
 
%timeit df['color1'] = 'red'; df['color1'].where(df['Set']=='Z','green')
%timeit df['color2'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit df['color3'] = np.where(df['Set']=='Z', 'red', 'green')
%timeit df['color4'] = df.Set.map(lambda x: 'red' if x == 'Z' else 'green')

397 ms ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
976 ms ± 241 ms per loop
673 ms ± 139 ms per loop
796 ms ± 182 ms per loop

3
如果你只有2个选择,请使用np.where()
df = pd.DataFrame({'A':range(3)})
df['B'] = np.where(df.A>2, 'yes', 'no')

如果你有超过两个选择,也许apply()方法可以发挥作用。

arr = pd.DataFrame({'A':list('abc'), 'B':range(3), 'C':range(3,6), 'D':range(6, 9)})

并且 arr 是

    A   B   C   D
0   a   0   3   6
1   b   1   4   7
2   c   2   5   8

如果你想让列 E 成为 如果 arr.A 是 'a',则 arr.B;否则,如果 arr.A 是 'b',则 arr.C;否则,如果 arr.A 是 'c',则 arr.D;否则,其他情况

arr['E'] = arr.apply(lambda x: x['B'] if x['A']=='a' else(x['C'] if x['A']=='b' else(x['D'] if x['A']=='c' else 1234)), axis=1)

最后,数组是这样的

    A   B   C   D   E
0   a   0   3   6   0
1   b   1   4   7   4
2   c   2   5   8   8

2

pyjanitorcase_when 函数是 pd.Series.mask 的封装,提供了一种可链接/方便的形式来处理多个条件:

对于单个条件:

df.case_when(
    df.col1 == "Z",  # condition
    "green",         # value if True
    "red",           # value if False
    column_name = "color"
    )

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

对于多个条件:

df.case_when(
    df.Set.eq('Z') & df.Type.eq('A'), 'yellow', # condition, result
    df.Set.eq('Z') & df.Type.eq('B'), 'blue',   # condition, result
    df.Type.eq('B'), 'purple',                  # condition, result
    'black',              # default if none of the conditions evaluate to True
    column_name = 'color'  
)
  Type  Set   color
1    A   Z  yellow
2    B   Z    blue
3    B   X  purple
4    C   Y   black

更多的例子可以在这里找到。

2

.apply()方法的一行代码如下:

df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')

之后,df数据框看起来像这样:
>>> print(df)
  Type Set  color
0    A   Z  green
1    B   Z  green
2    B   X    red
3    C   Y    red

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接