我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== 'Z',和颜色='红色'否则?

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

当前回答

如果你在处理海量数据,记忆方法是最好的:

# First create a dictionary of manually stored values
color_dict = {'Z':'red'}

# Second, build a dictionary of "other" values
color_dict_other = {x:'green' for x in df['Set'].unique() if x not in color_dict.keys()}

# Next, merge the two
color_dict.update(color_dict_other)

# Finally, map it to your column
df['color'] = df['Set'].map(color_dict)

当您有许多重复的值时,这种方法将是最快的。我的一般经验法则是记住data_size > 10**4 & n_distinct < data_size/4

在一种情况下,记忆10,000行,不同值不超过2,500。

其他回答

如果你在处理海量数据,记忆方法是最好的:

# First create a dictionary of manually stored values
color_dict = {'Z':'red'}

# Second, build a dictionary of "other" values
color_dict_other = {x:'green' for x in df['Set'].unique() if x not in color_dict.keys()}

# Next, merge the two
color_dict.update(color_dict_other)

# Finally, map it to your column
df['color'] = df['Set'].map(color_dict)

当您有许多重复的值时,这种方法将是最快的。我的一般经验法则是记住data_size > 10**4 & n_distinct < data_size/4

在一种情况下,记忆10,000行,不同值不超过2,500。

一个使用np.select的更简洁的方法:

a = np.array([['A','Z'],['B','Z'],['B','X'],['C','Y']])
df = pd.DataFrame(a,columns=['Type','Set'])

conditions = [
    df['Set'] == 'Z'
]

outputs = [
    'Green'
    ]
             # conditions Z is Green, Red Otherwise.
res = np.select(conditions, outputs, 'Red')
res 
array(['Green', 'Green', 'Red', 'Red'], dtype='<U5')
df.insert(2, 'new_column',res)    

df
    Type    Set new_column
0   A   Z   Green
1   B   Z   Green
2   B   X   Red
3   C   Y   Red

df.to_numpy()    
    
array([['A', 'Z', 'Green'],
       ['B', 'Z', 'Green'],
       ['B', 'X', 'Red'],
       ['C', 'Y', 'Red']], dtype=object)

%%timeit conditions = [df['Set'] == 'Z'] 
outputs = ['Green'] 
np.select(conditions, outputs, 'Red')

134 µs ± 9.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

df2 = pd.DataFrame({'Type':list('ABBC')*1000000, 'Set':list('ZZXY')*1000000})
%%timeit conditions = [df2['Set'] == 'Z'] 
outputs = ['Green'] 
np.select(conditions, outputs, 'Red')

188 ms ± 26.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

pyjanitor中的case_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

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

你可以使用pandas方法:

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

or

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

使用.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