for example:
A B
1 3 0
2 4 0
3 6 1
4 8 0
I'd like to know if there is a simple way to add for example 10 to the value of column A whene in B there is 1.
I'd like to have a df output like below.
A B
1 3 0
2 4 0
3 16 1
4 8 0
I've found something like the line of code below but this one replace the 6 with 1, I'd like to use that 6 to make some operations on it.
PS. pardón for my english
df.loc[df['B'] == 1, 'A'] = 1
You are close, use 10
with +=
:
#short version
df.loc[df['B'] == 1, 'A'] += 10
#long version
#df.loc[df['B'] == 1, 'A'] = 10 + df.loc[df['B'] == 1, 'A']
print (df)
A B
1 3 0
2 4 0
3 16 1
4 8 0
using np.where
df['A'] = np.where(df['B'] == 1,df['A'] + 10, df['A'])
Output
A B
1 3 0
2 4 0
3 16 1
4 8 0
One possible solution is to define a function with two parameters:
def cond_func(a,b):
if b = 1:
return a + 10
else:
return a
Then apply to each row in the dataframe
df['A'] = df.apply(lambda x: cond_func(x['A'], x['B'], axis=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.