Python Pandas - 将匹配行增加1

时间:2017-11-22 19:58:37

标签: python pandas

我有以下代码,其中数据帧d有两列,其中col1为字符串值,col2为int值。

我想找到与模式匹配的所有行(使用contains),然后将相应行的col2值增加1。在我的代码的最后一行,我试图增加一个,我得到以下错误:

  

SettingWithCopyWarning:尝试在a的副本上设置值   从DataFrame切片。尝试使用.loc [row_indexer,col_indexer] =   值而不是请参阅文档中的警告:   http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy   self [name] = value

import pandas as pd

d = {'col1': ['abc', 'ave','abd', 'ave','abe', 'ave'], 'col2': [0,1,0,1,0,1]}

df = pd.DataFrame(data=d)

#print(df[df.col1.str.contains("ab")])

df[df.col1.str.contains("ab")].col2 +=1

如何使用向量操作递增值。我试图避免循环。

2 个答案:

答案 0 :(得分:3)

为了好玩: - )

pd.to_numeric(df.col1.replace({'ab':1},regex=True),errors='coerce').fillna(0)+df.col2
Out[16]: 
0    1.0
1    1.0
2    1.0
3    1.0
4    1.0
5    1.0
dtype: float64

答案 1 :(得分:2)

让这个:

df['col2'] = df.col1.str.contains('ab').astype(int) + df.col2

df['col2'] += df.col1.str.contains('ab').mul(1)

输出:

  col1  col2
0  abc     1
1  ave     1
2  abd     1
3  ave     1
4  abe     1
5  ave     1
相关问题