有条件地创建series/dataframe列

ne5o7dgx  于 2021-09-29  发布在  Java
关注(0)|答案(10)|浏览(256)

我有一个数据框,大致如下所示:

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

我想在数据框中添加另一列(或生成一系列),其长度与设置颜色的数据框(记录/行数相等)相同 'green' 如果 Set == 'Z''red' 如果 Set 等于其他任何东西。
最好的方法是什么?

nx7onnlm

nx7onnlm1#

如果您只有两个选择:

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
ckocjqey

ckocjqey2#

列表理解是有条件地创建另一列的另一种方法。如果使用列中的对象数据类型,如示例中所示,列表理解通常优于大多数其他方法。
示例列表理解:

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
zzzyeukh

zzzyeukh3#

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

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

ecfsfe2w4#

下面是另一种剥猫皮的方法,使用字典将新值Map到列表中的键:

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']]
nnsrf1az

nnsrf1az5#

下面的方法比这里计时的方法慢,但是我们可以基于多个列的内容计算额外的列,并且可以为额外的列计算两个以上的值。
仅使用“设置”列的简单示例:

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来做这类事情(这似乎比使用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
zyfwsgd6

zyfwsgd66#

您只需使用强大的 .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

添加“颜色”列并将所有值设置为“红色”

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中用于布尔索引的逻辑运算符

dohp0rv5

dohp0rv57#

一班轮 .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
ijxebb2r

ijxebb2r8#

你可以使用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

输出:

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

x6492ojm9#

如果您使用的是海量数据,最好采用记忆方法:


# 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 e、 x.在一个案例中,用2500个或更少的不同值记录10000行。

lo8azlld

lo8azlld10#

如果只有两种选择,请使用 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)})

阿瑞斯

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

如果你想让e列 `if arr.A =='a' then arr.B elif arr.A=='b' then arr.C elif arr.A == 'c' then arr.D else something_else` ```
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

相关问题