Python Pandas : How to reshape the dataframe, specific cell to new column

You can use str.extract to extract the country name, then also use that to mask the valid rows:

countries = df['name'].str.extract('^country (.+)')[0]
df['country'] = countries.ffill()

df = df[countries.isna()]

Output

       name   age  gender    country
1       Ali  13.0    male      India
2       Abu  12.0    male      India
3      Acik  13.0    male      India
5   natasha  15.0  female  indonesia
6     jenny  43.0  female  indonesia
7      eric  23.0    male  indonesia
9       max  23.0    male  singapore
10    jason  32.0    male  singapore
11     jack  45.0    male  singapore

Alternative solution ::

(df.assign(country=df["name"].str.extract("^country (.+)", expand=False).ffill())
   .dropna()
 )

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top