[enter image description here][1] Hi - I was wondering if anybody can help me with this, I have the above table, and I want to create a new column 'D' based on the condition in column 'A'.
For example, if the last character of the string that is found in column A ends with a letter Z (s7-Z), multiply values in columns B and C and store it in a new column E. Else if the last character of the string that is found in column A ends with the letter I (s7-I) multiply the values in column C and D and store in column E.
CodePudding user response:
Something like this should get you started I guess:
import pandas as pd
import numpy as np
df=pd.DataFrame()
df['A']=pd.Series(['AZ','aI','aa'])
df['B']=pd.Series([2,3,4])
df['C']=pd.Series([5,2,3])
df['D']=pd.Series([10,20,30])
df['E']=np.where(df['A'].str.endswith('Z'),df['B']*df['C'],np.nan)
df['E']=np.where(df['A'].str.endswith('I'),df['C']*df['D'],df['E'])
df
the expression df['A'].str.endswith('Z') returns a series of boolean (True, False) indicating whether the string in each cell of df['A'] ends with 'Z'
np.where reads as np.where( This condition is true, Then bring this - in this case df['B']*df['C'], else - bring this - in this case NaN or the column 'E' itself)
Hope that makes sense... here are the docs for further exploration https://numpy.org/doc/stable/reference/generated/numpy.where.html https://pandas.pydata.org/docs/reference/api/pandas.Series.str.endswith.html