Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a column dataframe into list and read the first element

I have a data frame that looks like this

dataframe

name          address

Wings        3109 N Main St, Hope Mills, NC 28348   
Burger King  407 N Eastern Blvd, Fayetteville, NC 28301 

I am trying to convert the column address into a list to be able to get the fist element of each row: 3109 N Main St and 407 N Eastern Blvd

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far this is my code

df = pd.read_csv("mydataframe.csv")
df['address'] = list(df['address'])
df.loc[:, 'new_col'] = df.address.map(lambda x: x[0])

With this code I am getting the new_colum but I am getting the first character of the column address

name          address                                   new_col

Wings        3109 N Main St, Hope Mills, NC 28348          3
Burger King  407 N Eastern Blvd, Fayetteville, NC 28301    4

Expected Output

name          address                                   new_col

Wings        3109 N Main St, Hope Mills, NC 28348          3109 N Main St
Burger King  407 N Eastern Blvd, Fayetteville, NC 28301    407 N Eastern Blvd

>Solution :

df['new_col'] = df['address'].str.split(',',1).str[0]
df

    name            address                                     new_col
0   Wings           3109 N Main St, Hope Mills, NC 28348        3109 N Main St
1   Burger King     407 N Eastern Blvd, Fayetteville, NC 28301  407 N Eastern Blvd
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading