I have a dataframe:
df = pd.DataFrame(
{'number': ['10', '20' , '30', '40'], 'condition': ['A', 'B', 'A', 'B']})
df =
number condition
0 10 A
1 20 B
2 30 A
3 40 B
I want to apply a function to each element in a number column, as shown below:
df['number'] = df['number'].apply(lambda x: func(x))
BUT, although I am applying this function to a column of a number, I want the function to also refer to the column condition, i.e. in the pseudocode:
func(n):
For a single number and an example function, I would write:
number = 10
condition = A
def func(num, condition):
if condition == A:
return num*3
if condition == B:
return num*4
func(number,condition) = 15
How can I include the same function in my statement applywritten above? those. referring to the value in the condition column, acting on the value in the number column?
Note. I have read the docs on np.where(), pandas.loc()and pandas.index(), but I just can't figure out how to put this into practice.
, number condition.
, :
df =
number condition
0 30 A
1 80 B
2 90 A
3 160 B
: . . :
df1 = pd.DataFrame({'Entries':['man','guy','boy','girl'],'Conflict':['Yes','Yes','Yes','No']})
Entries Conflict
0 "man" "Yes"
1 "guy" "Yes"
2 "boy" "Yes"
3 "girl" "No
def funcA(d):
d = d + 'aaa'
return d
def funcB(d):
d = d + 'bbb'
return d
df1['Entries'] = np.where(df1['Conflict'] == 'Yes', funcA, funcB)
Output:
{'Conflict': ['Yes', 'Yes', 'Yes', 'Np'],
'Entries': array(<function funcB at 0x7f4acbc5a500>, dtype=object)}
np.where, pandas, , , :
:
Entries Conflict
0 "manaaa" "Yes"
1 "guyaaa" "Yes"
2 "boyaaa" "Yes"
3 "girlbbb" "No