我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== 'Z',和颜色='红色'否则?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== 'Z',和颜色='红色'否则?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
当前回答
使用.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
其他回答
如果你只有两种选择:
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。例如,如果你想要颜色
黄色时(df['设置']= = ' Z ') & (df(“类型”)= =“一”) 否则蓝色当(df['设置']= = ' Z ') & (df(“类型”)= = ' B ') 否则为紫色,当(df['Type'] == 'B') 否则黑,
然后使用
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
你可以使用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
另一种实现这一目标的方法是
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
您可以简单地使用强大的.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”列,并将所有值设置为“red”
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中用于布尔索引的逻辑运算符
列表推导式是有条件地创建另一列的另一种方法。如果您在列中使用对象dtype,就像您的示例一样,列表推导式通常优于大多数其他方法。
示例列表理解:
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%时间它测试:
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