mardi 11 mai 2021

Creating new dataframe column using string filter of other column

Below is the dataframe with column name 'Address'. I want to create a separate column 'City' with specific string using filter from Address column.

df1
Serial_No  Address 
1          India Gate Delhi
2          Delhi Redcross Hospital
3          Tolleyganj Bus Stand Kolkata
4          Kolkata Howrah
5          Katra Jammu

Below is the script that I am using

descr = []
col = 'City'
for col in df:
    if np.series(df[col]= df[df[col].str.contains('Delhi ', na=False)]:
        desc = 'Delhi'
    elif np.series(df[col]= df[df[col].str.contains('Kolkata ', na=False)]:
        desc = 'Kolkata'
    else:
        desc = 'None'

Below is the intended output

df1
Serial_No  Address                        City
1          India Gate Delhi               Delhi
2          Delhi Redcross Hospital        Delhi
3          Tolleyganj Bus Stand Kolkata   Kolkata
4          Kolkata Howrah                 Kolkata
5          Katra Jammu                    None

Aucun commentaire:

Enregistrer un commentaire