Reputation: 1309
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)
Upvotes: 0
Views: 130
Reputation: 4761
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
pandas.Series.str.split
pandas.Series.explode
pandas.Series.str.strip
pandas.Series.str.extract
pandas.Series.str.findall
pandas.DataFrame.reset_index
Upvotes: 1