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

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

Modifying value in dataframe column based on other column

问题

# 我有一个包含列A和B的数据框(df):

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

# 如果列A的值是'a',我想将列B的值乘以100,所以我的输出应该是:

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

请问是否有更简洁的方法来实现这个谢谢
英文:

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

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

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

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

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

答案1

得分: 4

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

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

与以下代码等效:

#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:

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

答案2

得分: 2

请尝试以下代码:

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

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

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

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

英文:

Could you please try following.

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

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

     A	B
0	'a'	5000
1	'b'	25
2	'a'	3000
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:

确定