我如何添加一个颜色列到下面的数据框架,使颜色='绿色'如果设置== '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
当前回答
如果只有两个选择,请使用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
其他回答
如果你在处理海量数据,记忆方法是最好的:
# 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。
这是另一种方法,使用字典将新值映射到列表中的键:
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']]
下面的方法比这里计时的方法慢,但是我们可以基于多个列的内容计算额外的列,并且可以为额外的列计算两个以上的值。
使用“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
您可以简单地使用强大的.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中用于布尔索引的逻辑运算符
如果只有两个选择,请使用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