Reputation:
I have a df with two columns number
,type
. I'm trying to remove the numbers in odd position if type
is change
and condition is odd
.
And Similarly numbers in even position if type
is change
and condition is even
.
For number - (7,14,21,28)
without numbers in odd
position - 7,21
.
Similarly - (3,6,5,8)
without numbers in even
position - 6,8
df
df= pd.DataFrame(data = {'number' : ['7,14,21,28', '2,5', '3,6,5,8 ', '4', '3,10,17,24,31'], 'type' : ['change', 'dont_change', 'change', 'dont_change', 'change'], 'condition':['odd','even','even','odd','odd']})
number type condition
0 7,14,21,28 change odd
1 2,5 dont_change even
2 3,6,5,8 change even
3 4 dont_change odd
4 3,10,17,24,31 change odd
My excepted output:
number type condition
0 7,21 change odd
1 2,5 dont_change even
2 6,8 change even
3 4 dont_change odd
4 3,17,31 change odd
What i have tried:
I have two different code for even and odd. Without adding type - condition - change/dont_change
string slicing with step = 2
even
df.number = np.where(df['condition'].eq('odd'), df.number.str.split(',').str[1::2].str.join(','), df['number'])
odd
df.number = np.where(df['condition'].eq('odd'), df.number.str.split(',').str[::2].str.join(','), df['number'])
How do i proceed from this?
Upvotes: 0
Views: 214
Reputation: 5012
Could you give this a shot?
def filter_numbers(row):
if row['type'] == 'change':
if row['condition'] == 'odd':
return ','.join(row['number'].split(',')[::2])
else:
return ','.join(row['number'].split(',')[1::2])
return row['number']
df['number'] = df.apply(filter_numbers, axis=1)
print(df)
Output:
number type condition
0 7,21 change odd
1 2,5 dont_change even
2 6,8 change even
3 4 dont_change odd
4 3,17,31 change odd
Upvotes: 0
Reputation: 323316
Let us try np.select
cond1=df['condition'].eq('odd') & df.type.eq('change')
cond2=df['condition'].eq('even') & df.type.eq('change')
v1=df.number.str.split(',').str[::2].str.join(',')
v2=df.number.str.split(',').str[1::2].str.join(',')
df.number=np.select([cond1,cond2], [v1,v2], default = df.number)
df
Out[417]:
number type condition
0 7,21 change odd
1 2,5 dont_change even
2 6,8 change even
3 4 dont_change odd
4 3,17,31 change odd
Upvotes: 1