仅在某些行的列上应用pandas函数

时间:2018-07-10 09:30:37

标签: python pandas

|   user  |       category    | val  | 
| ------  | ------------------| -----|
| user 1  | c1                |   3  |  
| user 1  | c2                |   4  |
| user 1  | c3                |   8  | 
| user 2  | c1                |   5  |
| user 2  | c2                |   9  | 
| user 2  | c3                |   10 |

比方说,我想将函数f应用于val列。返回数据帧的最佳方法是什么,例如,f仅应用于类别为c1的值?

|   user  |       category    | val     |
| ------  | ------------------| -----   | 
| user 1  | c1                |   f(3)  | 
| user 1  | c2                |   4     | 
| user 1  | c3                |   8     | 
| user 2  | c1                |  f(5)   | 
| user 2  | c2                |   9     |
| user 2  | c3                |   10    | 

1 个答案:

答案 0 :(得分:3)

使用numpy.where

df['val'] = np.where(df['category'] == 'c1', df['val'].apply(f), df['val'])

或使用loc进行过滤:

mask = df['category'] == 'c1'
df.loc[mask, 'val'] = df.loc[mask, 'val'].apply(f)