在基于其他列的情况下修改数据框列中的值

huangapple go评论151阅读模式
英文:

Modifying value in dataframe column based on other column

问题

  1. # 我有一个包含列A和B的数据框(df):
  2. A B
  3. 0 'a' 50
  4. 1 'b' 25
  5. 2 'a' 30
  6. 3 'c' 200
  7. # 如果列A的值是'a',我想将列B的值乘以100,所以我的输出应该是:
  8. A B
  9. 0 'a' 5000
  10. 1 'b' 25
  11. 2 'a' 3000
  12. 3 'c' 200
  13. 请问是否有更简洁的方法来实现这个谢谢
英文:

I have a dataframe(df) with column A and B:

  1. A B
  2. 0 'a' 50
  3. 1 'b' 25
  4. 2 'a' 30
  5. 3 'c' 200

I want to multiply value of column B by 100 if column A value is 'a' so my output should be:

  1. A B
  2. 0 'a' 5000
  3. 1 'b' 25
  4. 2 'a' 3000
  5. 3 'c' 200

Could anyone please suggest a cleaner way to do this. Thanks.

答案1

得分: 4

我认为测试子字符串是不必要的,只需使用DataFrame.loc与比较值a

  1. df.loc[df['A'] == 'a', 'B'] *= 100
  2. #print (df)
  3. A B
  4. 0 a 5000
  5. 1 b 25
  6. 2 a 3000
  7. 3 c 200

与以下代码等效:

  1. #df.loc[df['A'] == 'a', 'B'] = df.loc[df['A'] == 'a', 'B'] * 100
英文:

I think test substrings is not necessary, only use DataFrame.loc with compare value a:

  1. df.loc[df['A'] == "'a'", 'B'] *= 100
  2. #same like
  3. #df.loc[df['A'] == "'a'", 'B'] = df.loc[df['A'] == "'a'", 'B'] * 100
  4. print (df)
  5. A B
  6. 0 a 5000
  7. 1 b 25
  8. 2 a 3000
  9. 3 c 200

答案2

得分: 2

请尝试以下代码:

  1. df['B'] = np.where(df['A'] == 'a', df['B'] * 100, df['B'])

运行上述代码后,DataFrame 的值将如下所示:

  1. A B
  2. 0 'a' 5000
  3. 1 'b' 25
  4. 2 'a' 3000
  5. 3 'c' 200

可以阅读np.where以了解有关np.where的更多信息。

英文:

Could you please try following.

  1. df['B']=np.where(df['A']=="'a'",df['B']*100,df['B'])

After running above code, value of dataframe will be as follows.

  1. A B
  2. 0 'a' 5000
  3. 1 'b' 25
  4. 2 'a' 3000
  5. 3 'c' 200

np.where could be read for knowing about np.where

答案3

得分: 0

df.loc[df["A"] == "a", "B"] *= 100 或者如果需要其他操作,可以使用 where 函数。但对于这个情况,这已经足够了。

英文:

df.loc[df["A"] == "a", "B"] *= 100

or you can use where function if you need something else. However for this case, it will be enough.

huangapple
  • 本文由 发表于 2020年1月3日 14:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定