> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to Split Strings and Extract the N-th Element in a Pandas DataFrame
- URL: https://datascientyst.com/how-to-split-strings-and-extract-the-n-th-element-in-a-pandas-dataframe/
- Published: 2025-03-18T05:05:37.000Z
- Updated: 2025-03-18T05:05:37.000Z
- Author: John D K
- Tags: split()

Working with text data in Pandas, you may need to split strings based on a n-th occuramce of delimiter and extract specific parts.

This is useful for parsing URLs, file paths, or structured data. Pandas provides efficient ways to handle such operations with `str.split()` and `expand=True`.

**(1) Split the string at the nth occurrence and keep the first part**

```python
df['column_name'].str.split('-', n=2).str[0]

```

**(2) Extract the nth part from a split string**

```python
df['column_name'].str.split('-', expand=True)[2]

```

## 1\. Sample data

```python
import pandas as pd

data = ['https://example.com/search?q=avatar', 
        'https://example.com/profile/avatar', 
        'https://example.com/map']
df = pd.DataFrame({'text': data})

df

```

data looks like:

|   | text                                | first\_three |
| - | ----------------------------------- | ------------ |
| 0 | https://example.com/search?q=avatar | https:       |
| 1 | https://example.com/profile/avatar  | https:       |
| 2 | https://example.com/map             | https:       |

## 2\. Splitting a String at the n-th Occurrence

To split a string only at the n-th occurrence of a delimiter, use the `n` parameter of `str.split()`. We can extract the last part of the URL by:

```python
df['text'].str.split('/', n=3, expand=True)[3]

```

**Output:**

```
0    search?q=avatar
1     profile/avatar
2                map
Name: 3, dtype: object

```

- `n=3` ensures only 3 splits occur
- `[3]` extracts the 3rd part of the split

below you can find the resulted dataframe from the split:

|   | 0      | 1 | 2           | 3               |
| - | ------ | - | ----------- | --------------- |
| 0 | https: |   | example.com | search?q=avatar |
| 1 | https: |   | example.com | profile/avatar  |
| 2 | https: |   | example.com | map             |

## 3\. Extracting the nth Element from a Split String

If you need to extract the nth part of the split string, use `expand=True` to create multiple columns.

```python
df[['protocol', 'empty', 'domain', 'method', 'param']] = df['text'].str.split('/', expand=True)
df

```

**Output:**

|   | text                                | first\_three | protocol | empty | domain      | method          | param  |
| - | ----------------------------------- | ------------ | -------- | ----- | ----------- | --------------- | ------ |
| 0 | https://example.com/search?q=avatar | https:       | https:   |       | example.com | search?q=avatar | None   |
| 1 | https://example.com/profile/avatar  | https:       | https:   |       | example.com | profile         | avatar |
| 2 | https://example.com/map             | https:       | https:   |       | example.com | map             | None   |

## 4\. Keeping Only the Last Two Parts of a Split String

For cases like domain extraction (`example.com`, `www.example.com`), keep only the last two parts. Or keep the domain and the method from URL:

```python
df['text'].apply(lambda x: '/'.join(x.split('/')[-2:]))

```

**Output:**

```
0    example.com/search?q=avatar
1                 profile/avatar
2                example.com/map
Name: text, dtype: object

```

- `x.split('/')[-2:]` keeps only the last two elements.
- `'/'.join(...)` reconstructs the truncated string.

## 5\. Conclusion

Pandas provides multiple ways to split strings based on the nth occurrence of a delimiter. Whether you need to keep a portion of the string, extract a specific element, or retain only the last few parts, `str.split()` and `apply()` are effective tools for data transformation.

---

### **Resources**

- [Pandas str.split() Documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html?ref=datascientyst.com)
- [StackOverflow: Splitting String in a Pandas DataFrame](https://stackoverflow.com/questions/14745022/how-to-split-a-column-into-multiple-columns-in-pandas?ref=datascientyst.com)
- [Splitting nth elements in a string in a pandas dataframe](https://stackoverflow.com/questions/71764317/splitting-nth-elements-in-a-string-in-a-pandas-dataframe?ref=datascientyst.com)
- [How to Strip a String After the Nth Occurrence of a Character in Python](https://softhints.com/how-to-strip-a-string-after-the-nth-occurrence-of-a-character-in-python/?ref=datascientyst.com)