| 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 |
答案 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)