Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

Combining specific rows in a pandas dataframe into a new row

I have a pandas dataframe and for one of my columns, I need to combine some of the values however I'm not sure what function to use (merge, sum, concatenate, etc.) I have a dataframe with 5 columns (postal code, borough, neighbourhood, latitude, longitude) and for the borough column, there are 10 unique boroughs however I need it to be 6 boroughs only, therefore I need to combine 4 of the boroughs(East Toronto, Downtown Toronto, West Toronto and Central Toronto)enter image description here into one borough and name this borough Old Toronto. How do I do this without losing all the neighbourhoods in the boroughs which I need to combine?

question from:https://stackoverflow.com/questions/66061898/combining-specific-rows-in-a-pandas-dataframe-into-a-new-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Replace them like below:

l=['East Toronto', 'Downtown Toronto', 'West Toronto', 'Central Toronto']

df['borough']=df['borough'].str.replace('|'.join(l),"Old Toronto")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...