python - Pandas 条件创建多列

标签 python pandas dataframe

假设我有一个这样的数据框:

x y z class
1 2 3   0
2 2 3   0
1 4 5   2
3 2 2   1

我想为每个类分配不同的颜色值 (RGB)。所以我需要根据 class 在列 z 之后插入三列:

x y z  r   g   b class
1 2 3 255 254 253  0
2 2 3 255 254 253  0
1 4 5  0  255  0   2
3 2 2  0   0  255  1

目前我是这样做的:

# insert three columns
df['r']=0
df['g']=0
df['b']=0
# replace r/g/b values based on `class`
def colorit(dataframe):
    colors = [[255, 254, 253], [0, 0, 255], [0, 255, 0]]
    for i in range(3):
        dataframe.loc[dataframe['c']==i, 'r'] = colors[i][0]
        dataframe.loc[dataframe['c']==i, 'g'] = colors[i][1]
        dataframe.loc[dataframe['c']==i, 'b'] = colors[i][2]

但我认为应该有一些方法可以利用 applymap 方法或类似的方法来更优雅、更高效地完成此操作(使用更少的代码并且没有循环)。

最佳答案

你可以做

In [237]: df.assign(**pd.DataFrame([colors[x] for x in df['class']], columns=['r', 'g', 'b']))
Out[237]:
   x  y  z  class    r    g    b
0  1  2  3      0  255  254  253
1  2  2  3      0  255  254  253
2  1  4  5      2    0  255    0
3  3  2  2      1    0    0  255

详细信息

In [238]: df
Out[238]:
   x  y  z  class
0  1  2  3      0
1  2  2  3      0
2  1  4  5      2
3  3  2  2      1

In [239]: colors
Out[239]: [[255, 254, 253], [0, 0, 255], [0, 255, 0]]

关于python - Pandas 条件创建多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098568/

相关文章:

python - python中的整数平方根

python - 根据 Pandas 中另一列中值的间隔选择列中值的范围

python - dynamodb管道对象到pandas数据帧

python - pd.update 有两个匹配的行

python - Pandas 数据框中的前填充和后填充缺失组值

python - 根据 Pandas 上的列值应用 lambda

python - 根据另一列查找公共(public)列值

python-3.x - 创建一个新列,在同一行上使用最少的其他列

python - Pandas 在多索引 DataFrame 中使用 loc 进行赋值

R:在数据框中定义一个因素的水平