Reputation: 521
I have a dataframe:
Data = {'group': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
}
current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
I want to set value2
to zero if corresponding value1
is equal to zero while keeping all other values the same. So my desired result would be:
Data = {'group': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
}
current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
How could I do this?
Upvotes: 0
Views: 917
Reputation: 13
def change_value(row):
if row.value1 == 0:
row.value2 = 0
return row
current_result = current_result.apply(change_value, axis=1)
Upvotes: 0
Reputation: 140
Use this:
current_result.loc[current_result['value1'] == 0, ['value2']] = 0
Upvotes: 1
Reputation: 7539
Without using any Pandas core features, this loop gets the job done:
for index, value in enumerate(current_result["value1"]):
if value == 0:
current_result["value2"][index] = 0
Upvotes: 0
Reputation: 863741
You can multiple by boolean mask - True
are processes like 1
,False
like 0
so compare for not equal 0
by Series.ne
:
current_result['value2'] *= current_result['value1'].ne(0)
print (current_result)
group value1 value2
0 a 2 25
1 b 0 0
2 c 0 0
3 d 5 11
4 e 5 36
5 f 5 3
6 g 6 65
7 h 31 6
8 i 7 89
9 j 5 8
10 k 0 0
11 l 99 5
Upvotes: 2