英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论