问题:熊猫有条件地创建系列/数据框列
我有下面的数据框:
Type Set
1 A Z
2 B Z
3 B X
4 C Y
我想向数据框添加另一列(或生成一系列),该列的长度与数据框的长度相同(=记录/行的数目相等),如果Set =’Z’则设置为绿色,如果Set =’否则为’red’ 。
最好的方法是什么?
回答 0
如果您只有两个选择供您选择:
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)
Yield
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
回答 1
列表理解是有条件创建另一列的另一种方法。如果像在示例中那样使用列中的对象dtype,则列表理解通常胜过大多数其他方法。
示例列表理解:
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
回答 2
可以实现这一目标的另一种方法是
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
回答 3
这是给这只猫换皮的另一种方法,使用字典将新值映射到列表中的键上:
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-type语句(即要替换的许多唯一值)时,此方法可能非常强大。
当然,您可以始终这样做:
df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)
但是apply在我的机器上,这种方法的速度是上面的方法的三倍以上。
您也可以使用dict.get:
df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]
回答 4
以下内容比此处介绍的方法要慢,但是我们可以根据多于一列的内容来计算额外的列,并且可以为额外的列计算两个以上的值。
仅使用“设置”列的简单示例:
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来执行这种操作(尽管这似乎比使用assignand 还要慢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
回答 5
也许是通过更新Pandas来实现的,但到目前为止,我认为以下是该问题的最短和最佳答案。您可以使用该.loc方法,并根据需要使用一个或多个条件。
代码摘要:
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中用于布尔索引的逻辑运算符
回答 6
一种带有.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
回答 7
如果您要处理海量数据,则最好采用记忆方式:
# 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个或更少的不同值。

