我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== '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。

当你有一个或几个条件时,可以使用下面的简单语句:

df['color'] = np.select(condlist=[df['Set']=="Z", df['Set']=="Y"], choicelist=["green", "yellow"], default="red")

容易,很好去!

更多信息请访问:https://numpy.org/doc/stable/reference/generated/numpy.select.html

另一种实现这一目标的方法是

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

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

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

如果只有两个选择,请使用np.where()

df = pd.DataFrame({'A':range(3)})
df['B'] = np.where(df.A>2, 'yes', 'no')

如果你有超过2个选择,也许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 elif arr。A=='b' then arr. c elif 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)

最后是arr

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