python Pandas替换字符串中的单词

时间:2017-04-22 06:03:34

标签: python pandas

给出如下数据框:

A    B    C
1    a    yes
2    b    yes
3    a    no

我想将数据框更改为:

A    B    C
1    a    yes
2    b    no
3    a    no

这意味着如果列B的值为'b',我想将列C更改为'no'。哪个可以用df[df['B']=='b']['C'].str.replace('yes','no')表示。但是使用它不会改变数据帧df本身。即使我试过df[df['B']=='b']['C'] = df[df['B']=='b']['C'].str.replace('yes','no')它也没用。我想知道如何解决这个问题。

2 个答案:

答案 0 :(得分:5)

mask设置值的解决方案:

df.loc[df.B == 'b', 'C'] = 'no'
print (df)
   A  B    C
0  1  a  yes
1  2  b   no
2  3  a   no

df['C'] = df['C'].mask(df.B == 'b','no')
print (df)
   A  B    C
0  1  a  yes
1  2  b   no
2  3  a   no

仅替换yes字符串的解决方案:

df.loc[df.B == 'b', 'C'] = df['C'].replace('yes', 'no')
print (df)
   A  B    C
0  1  a  yes
1  2  b   no
2  3  a   no

df['C'] = df['C'].mask(df.B == 'b', df['C'].replace('yes', 'no'))
print (df)
   A  B    C
0  1  a  yes
1  2  b   no
2  3  a   no

在更改的df中更好地看到差异:

print (df)
   A  B        C
0  1  a      yes
1  2  b      yes
2  3  b  another
3  4  a       no

df['C_set'] = df['C'].mask(df.B == 'b','no')
df['C_replace'] = df['C'].mask(df.B == 'b', df['C'].replace('yes', 'no'))

print (df)
   A  B        C C_set C_replace
0  1  a      yes   yes       yes
1  2  b      yes    no        no
2  3  b  another    no   another
3  4  a       no    no        no

编辑:

在您的解决方案中,只需添加loc

df.loc[df['B']=='b', 'C'] = df.loc[df['B']=='b', 'C'].str.replace('yes','no')
print (df)
   A  B        C
0  1  a      yes
1  2  b       no
2  3  b  another
3  4  a       no

EDIT1:

我真的很好奇什么方法最快:

#[40000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)    
print (df)

In [37]: %timeit df.loc[df['B']=='b', 'C'] = df['C'].str.replace('yes','no')
10 loops, best of 3: 79.5 ms per loop

In [38]: %timeit df.loc[df['B']=='b', 'C'] = df.loc[df['B']=='b','C'].str.replace('yes','no')
10 loops, best of 3: 48.4 ms per loop

In [39]: %timeit df.loc[df['B']=='b', 'C'] = df.loc[df['B']=='b', 'C'].replace('yes','no')
100 loops, best of 3: 14.1 ms per loop

In [40]: %timeit df['C'] = df['C'].mask(df.B == 'b', df['C'].replace('yes', 'no'))
100 loops, best of 3: 10.1 ms per loop

# piRSquared solution with replace
In [53]: %timeit df.C = np.where(df.B.values == 'b', df.C.replace('yes', 'no'), df.C.values)
100 loops, best of 3: 4.74 ms per loop

EDIT1:

更好的是更改条件 - 如果需要最快的解决方案,请添加df.C == 'yes'df.C.values == 'yes'

df.loc[(df.B == 'b') & (df.C == 'yes'), 'C'] = 'no'

df.C = np.where((df.B.values == 'b') & (df.C.values == 'yes'), 'no', df.C.values)

答案 1 :(得分:4)

<强> np.where

df.C = np.where(df.B == 'b', 'no', df.C)

或者

df.C = np.where(df.B.values == 'b', 'no', df.C.values)

<强> pd.Series.mask

df.C = df.C.mask(df.B == 'b', 'no')

所有更改df到位并产量

   A  B    C
0  1  a  yes
1  2  b   no
2  3  a   no

时间 enter image description here