熊猫数据框的选择性乘法

时间:2019-03-31 16:31:48

标签: python-3.x pandas

我有一个表单的pandas Dataframe和Series

df = pd.DataFrame({'Key':[2345,2542,5436,2468,7463],
                   'Segment':[0] * 5,
                   'Values':[2,4,6,6,4]})
print (df)
    Key  Segment  Values
0  2345        0       2
1  2542        0       4
2  5436        0       6
3  2468        0       6
4  7463        0       4

s = pd.Series([5436, 2345])
print (s)
0    5436
1    2345
dtype: int64

在原始df中,我希望将第三列(值)乘以7,但该系列中存在的键除外。所以我的最终df应该看起来像

enter image description here

在Python 3.x中实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

DataFrame.locSeries.isin一起用于过滤条件Value的过滤器df.loc[~df['Key'].isin(s), 'Values'] *= 7 print (df) Key Segment Values 0 2345 0 2 1 2542 0 28 2 5436 0 6 3 2468 0 42 4 7463 0 28 列,以实现非隶属关系且标量乘以倍数:

{{1}}

答案 1 :(得分:0)

另一种方法可能是使用numpy.where():

df['Values'] *= np.where(~df['Key'].isin([5436, 2345]), 7,1)