首页 > 解决方案 > 如何根据 ID 号列表乘以列值?

问题描述

我有一个数据集,想根据列表的 ID 值将值列乘以 2.5。

我的数据框看起来像这样

  Name    ID   Salary 
  James   21   25,000
  Sam     12   15,000

我的列表是一个系列,我们称它为 s = ["21", "36"] 这个数据是 ID 号

如何根据身份证号码将工资乘以2.5?

目标是拥有这样的东西

  Name    ID   Salary 
  James   21   62,500
  Sam     12   15,000

标签: pythonpandasdataframedataset

解决方案


首先转换Salary为数字,然后将值转换ID为字符串,test bySeries.isin和 multiple byDataFrame.loc以通过掩码选择行和按名称选择列Salary

s = ["21", "36"]

#if values of Salary are strings
#df = pd.read_csv(file, thousands=',')
#or
#df['Salary'] = df['Salary'].str.replace(',','').astype(int)

#ID are converted to strings by `astype`, because valus in list s are strings
df.loc[df['ID'].astype(str).isin(s), 'Salary'] *= 2.5
#if s are numeric
#df.loc[df['ID'].isin(s), 'Salary'] *= 2.5
print (df)
    Name  ID   Salary
0  James  21  62500.0
1    Sam  12  15000.0

推荐阅读