【问题标题】:How to Multiply a column value based on a list of ID numbers?如何根据 ID 号列表乘以列值?
【发布时间】:2019-12-30 06:46:49
【问题描述】:

我有一个数据集,想根据列表的 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

【问题讨论】:

    标签: python pandas dataframe dataset


    【解决方案1】:

    首先将Salary 转换为数字,然后将ID 的值转换为字符串,通过Series.isin 测试并通过DataFrame.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
    

    【讨论】:

    • 如果我的薪水是 float64 怎么办?
    • @amythomspon - 然后省略 df['Salary'] = df['Salary'].str.replace(',','').astype(int)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多