How do I split a long string by the first space unless the second word is lower case?
df col
0 Apple The fruit. 20 Banana tree A fruit. 30 Carrot A Vegetable. 40
Expected Output:
df
fruit definition page
0 Apple The fruit. 20
1 Banana tree A fruit. 30
2 Carrot A Vegetable. 40
df.col.str.split('(\d+)').explode()
0 Apple The fruit.
0 20
0 Banana tree A fruit.
0 30
0 Carrot A Vegetable.
0 40
df.col.split(".", expand = True)
You can do it this way:
new_df = pd.DataFrame()
new_df[["fruit", "definition"]] = df.col.str.split("\d+")\
.str[:-1].explode()\
.str.strip()\
.str.extract(r'^([A-Z][^A-Z]*)(.*)')
new_df["page"] = df.col.str.findall('\d+').explode()
new_df = new_df.reset_index(drop = True)
new_df
fruit definition page
0 Apple The fruit. 20
1 Banana tree A fruit. 30
2 Carrot A Vegetable. 40
Documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.