asd
asd

Reputation: 1309

String split on digit and space

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

Answers (1)

Pablo C
Pablo C

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

  1. pandas.Series.str.split
  2. pandas.Series.explode
  3. pandas.Series.str.strip
  4. pandas.Series.str.extract
  5. pandas.Series.str.findall
  6. pandas.DataFrame.reset_index

Upvotes: 1

Related Questions