我有一个数据框,大致如下所示:
Type Set1 A Z2 B Z 3 B X4 C Y
Type Set
1 A Z
2 B Z
3 B X
4 C Y
我想在数据框中添加另一列(或生成一系列),其长度与设置颜色的数据框(记录/行数相等)相同 'green' 如果 Set == 'Z' 及 'red' 如果 Set 等于其他任何东西。最好的方法是什么?
'green'
Set == 'Z'
'red'
Set
nx7onnlm1#
如果您只有两个选择:
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
例如
import pandas as pdimport numpy as npdf = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})df['color'] = np.where(df['Set']=='Z', 'green', 'red')print(df)
import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
print(df)
产量
Set Type color0 Z A green1 Z B green2 X B red3 Y C red
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 ,然后使用
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)
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')
产生
Set Type color0 Z A yellow1 Z B blue2 X B purple3 Y C black
0 Z A yellow
1 Z B blue
2 X B purple
3 Y C black
ckocjqey2#
列表理解是有条件地创建另一列的另一种方法。如果使用列中的对象数据类型,如示例中所示,列表理解通常优于大多数其他方法。示例列表理解:
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit测试:
import pandas as pdimport numpy as npdf = 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 loop1000 loops, best of 3: 523 µs per loop1000 loops, best of 3: 263 µs per loop
%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
zzzyeukh3#
实现这一目标的另一种方法是
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
ecfsfe2w4#
下面是另一种剥猫皮的方法,使用字典将新值Map到列表中的键:
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,))
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,))
它看起来像什么:
dfOut[2]: INDICATOR VALUE NEW_VALUE0 A 10 11 B 9 22 C 8 33 D 7 4
df
Out[2]:
INDICATOR VALUE NEW_VALUE
0 A 10 1
1 B 9 2
2 C 8 3
3 D 7 4
当您有许多问题时,这种方法可能非常强大 ifelse -键入要生成的语句(即许多要替换的唯一值)。当然,你也可以这样做:
ifelse
df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)
但这一方法的速度是传统方法的三倍多 apply 从上面接近,在我的机器上。你也可以这样做,使用 dict.get :
apply
dict.get
df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]
nnsrf1az5#
下面的方法比这里计时的方法慢,但是我们可以基于多个列的内容计算额外的列,并且可以为额外的列计算两个以上的值。仅使用“设置”列的简单示例:
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)
def set_color(row):
if row["Set"] == "Z":
return "red"
else:
return "green"
df = df.assign(color=df.apply(set_color, axis=1))
Set Type color0 Z A red1 Z B red2 X B green3 Y C green
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)
elif row["Type"] == "C":
return "blue"
Set Type color0 Z A red1 Z B red2 X B green3 Y C blue
3 Y C blue
也可以使用plydata来做这类事情(这似乎比使用plydata更慢) assign 及 apply (尽管如此)。
assign
from plydata import define, if_else
简单的 if_else :
if_else
df = define(df, color=if_else('Set=="Z"', '"red"', '"green"'))print(df)
df = define(df, color=if_else('Set=="Z"', '"red"', '"green"'))
嵌套 if_else :
df = define(df, color=if_else( 'Set=="Z"', '"red"', if_else('Type=="C"', '"green"', '"blue"')))print(df)
df = define(df, color=if_else(
'Set=="Z"',
'"red"',
if_else('Type=="C"', '"green"', '"blue"')))
Set Type color0 Z A red1 Z B red2 X B blue3 Y C green
2 X B blue
zyfwsgd66#
您只需使用强大的 .loc 方法,并根据需要使用一个或多个条件(使用pandas=1.0.5进行测试)。代码摘要:
.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['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 so far:
0 A Z
1 B Z
2 B X
3 C Y
添加“颜色”列并将所有值设置为“红色”
应用您的单一条件:
df.loc[(df['Set']=="Z"), 'Color'] = "green"# df: Type Set Color0 A Z green1 B Z green2 B X red3 C Y red
# df:
Type Set Color
0 A Z green
1 B Z green
2 B X red
3 C Y red
或多个条件(如果需要):
您可以在此处阅读pandas逻辑运算符和条件选择:pandas中用于布尔索引的逻辑运算符
dohp0rv57#
一班轮 .apply() 方法如下:
.apply()
df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')
之后, df 数据框如下所示:
>>> print(df) Type Set color0 A Z green1 B Z green2 B X red3 C Y red
>>> print(df)
Type Set color
ijxebb2r8#
你可以使用Pandas的方法 where 及 mask :
where
mask
df['color'] = 'green'df['color'] = df['color'].where(df['Set']=='Z', other='red')# Replace values where the condition is False
df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False
或
df['color'] = 'red'df['color'] = df['color'].mask(df['Set']=='Z', other='green')# Replace values where the condition is True
df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True
输出:
Type Set color1 A Z green2 B Z green3 B X red4 C Y red
1 A Z green
2 B Z green
3 B X red
4 C Y red
x6492ojm9#
如果您使用的是海量数据,最好采用记忆方法:
# First create a dictionary of manually stored valuescolor_dict = {'Z':'red'}# Second, build a dictionary of "other" valuescolor_dict_other = {x:'green' for x in df['Set'].unique() if x not in color_dict.keys()}# Next, merge the twocolor_dict.update(color_dict_other)# Finally, map it to your columndf['color'] = df['Set'].map(color_dict)
# 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 e、 x.在一个案例中,用2500个或更少的不同值记录10000行。
data_size
10**4
n_distinct
data_size/4
lo8azlld10#
如果只有两种选择,请使用 np.where() ```df = pd.DataFrame({'A':range(3)})df['B'] = np.where(df.A>2, 'yes', 'no')
np.where()
如果你有两个以上的选择,也许 `apply()` 可以工作输入
arr = pd.DataFrame({'A':list('abc'), 'B':range(3), 'C':range(3,6), 'D':range(6, 9)})
阿瑞斯
A B C D0 a 0 3 61 b 1 4 72 c 2 5 8
如果你想让e列 `if arr.A =='a' then arr.B elif arr.A=='b' then arr.C elif arr.A == 'c' then arr.D else something_else` ```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)
如果你想让e列 `if arr.A =='a' then arr.B elif arr.A=='b' then arr.C elif arr.A == 'c' then arr.D else something_else` ```
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 E0 a 0 3 6 01 b 1 4 7 42 c 2 5 8 8
A B C D E
0 a 0 3 6 0
1 b 1 4 7 4
2 c 2 5 8 8
10条答案
按热度按时间nx7onnlm1#
如果您只有两个选择:
例如
产量
如果您有两种以上的情况,请使用
np.select
. 例如,如果你想color
成为yellow
什么时候(df['Set'] == 'Z') & (df['Type'] == 'A')
否则blue
什么时候(df['Set'] == 'Z') & (df['Type'] == 'B')
否则purple
什么时候(df['Type'] == 'B')
否则black
,然后使用
产生
ckocjqey2#
列表理解是有条件地创建另一列的另一种方法。如果使用列中的对象数据类型,如示例中所示,列表理解通常优于大多数其他方法。
示例列表理解:
%timeit测试:
zzzyeukh3#
实现这一目标的另一种方法是
ecfsfe2w4#
下面是另一种剥猫皮的方法,使用字典将新值Map到列表中的键:
它看起来像什么:
当您有许多问题时,这种方法可能非常强大
ifelse
-键入要生成的语句(即许多要替换的唯一值)。当然,你也可以这样做:
但这一方法的速度是传统方法的三倍多
apply
从上面接近,在我的机器上。你也可以这样做,使用
dict.get
:nnsrf1az5#
下面的方法比这里计时的方法慢,但是我们可以基于多个列的内容计算额外的列,并且可以为额外的列计算两个以上的值。
仅使用“设置”列的简单示例:
考虑更多颜色和更多列的示例:
编辑(2019年6月21日):使用plydata
也可以使用plydata来做这类事情(这似乎比使用plydata更慢)
assign
及apply
(尽管如此)。简单的
if_else
:嵌套
if_else
:zyfwsgd66#
您只需使用强大的
.loc
方法,并根据需要使用一个或多个条件(使用pandas=1.0.5进行测试)。代码摘要:
说明:
添加“颜色”列并将所有值设置为“红色”
应用您的单一条件:
或多个条件(如果需要):
您可以在此处阅读pandas逻辑运算符和条件选择:pandas中用于布尔索引的逻辑运算符
dohp0rv57#
一班轮
.apply()
方法如下:之后,
df
数据框如下所示:ijxebb2r8#
你可以使用Pandas的方法
where
及mask
:或
输出:
x6492ojm9#
如果您使用的是海量数据,最好采用记忆方法:
当您有许多重复的值时,这种方法将是最快的。我的一般经验法则是在以下情况下进行记忆:
data_size
>10**4
&n_distinct
<data_size/4
e、 x.在一个案例中,用2500个或更少的不同值记录10000行。lo8azlld10#
如果只有两种选择,请使用
np.where()
```df = pd.DataFrame({'A':range(3)})
df['B'] = np.where(df.A>2, 'yes', 'no')
arr = pd.DataFrame({'A':list('abc'), 'B':range(3), 'C':range(3,6), 'D':range(6, 9)})
A B C D
0 a 0 3 6
1 b 1 4 7
2 c 2 5 8
最后是arr