我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== '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
当前回答
另一种实现这一目标的方法是
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
其他回答
如果你只有两种选择:
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
下面的方法比这里计时的方法慢,但是我们可以基于多个列的内容计算额外的列,并且可以为额外的列计算两个以上的值。
使用“Set”列的简单示例:
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
编辑(21/06/2019):使用plydata
也可以使用plydata来做这类事情(不过,这似乎比使用assign和apply还要慢)。
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
另一种实现这一目标的方法是
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
一个使用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)
如果你在处理海量数据,记忆方法是最好的:
# 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。