0

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

2 Answers 2

2

Let us try str.extract

df['new'] = df.Address.str.extract(('(Delhi|Kolkata)'))[0]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

import pandas as pd
df1=pd.DataFrame([[1,'India Gate Delhi'],[2,'Delhi Redcross Hospital'],[3,'Tolleyganj Bus Stand Kolkata'],[4,'Kolkata Howrah'],[5,'Katra Jammu']],columns=['Serial_No','Address'])
print(df1)

def f(df1):
    if 'Delhi' in df1['Address']:
        val = 'Delhi'
    elif 'Kolkata' in df1['Address']:
        val = 'Kolkata'
    else:
        val = 'None'
    return val
df1['City'] = df1.apply(f, axis=1)
print(df1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.