Reputation: 37
So I have a dataframe that looks like this:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.zeros(8)})
The output looks like this:
print(df)
A B C D
0 foo one 0 0.0
1 bar one 1 0.0
2 foo two 2 0.0
3 bar three 3 0.0
4 foo two 4 0.0
5 bar two 5 0.0
6 foo one 6 0.0
7 foo three 7 0.0
What I now want to do is consider column C and if its values are odd numbers, change the corresponding D value to 1 and if they are even, keep it 0.
How do I do that? I am very new to python and I am kind of confused. Any help would be appreciated.
Upvotes: 2
Views: 19
Reputation: 150745
Is it:
df['D'] = df['C'] % 2
Or if current 0
values in D
are just representative, and you only want to change the specific rows, you can use loc
:
df.loc[(df['C'] % 2)==1, 'D'] = 1
Output:
A B C D
0 foo one 0 0
1 bar one 1 1
2 foo two 2 0
3 bar three 3 1
4 foo two 4 0
5 bar two 5 1
6 foo one 6 0
7 foo three 7 1
Upvotes: 2