我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== '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')
其他回答
这是另一种方法,使用字典将新值映射到列表中的键:
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']]
列表推导式是有条件地创建另一列的另一种方法。如果您在列中使用对象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
如果只有两个选择,请使用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
另一种实现这一目标的方法是
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