Reputation: 103
I have a column in my pandas dataframe that includes communes of French cities. Here is an example:
index | Com |
---|---|
1 | Paris 3 |
2 | Paris 17 |
3 | Marseille 5 |
4 | Abainville |
5 | Aast |
6 | Marseille 15 |
7 | Lyon 4 |
Except I would like to add a 0 to the single digit numbers to get this:
index | Com |
---|---|
1 | Paris 03 |
2 | Paris 17 |
3 | Marseille 05 |
4 | Abainville |
5 | Aast |
6 | Marseille 15 |
7 | Lyon 04 |
What can I do?
Upvotes: 3
Views: 1233
Reputation: 133458
With your shown samples, please try following. Using Pandas str.replace
function.
df['Com'].str.replace(r"^(\S+)(\s+)(\d)$", r"\g<1>\g<2>0\g<3>")
Output will be as follows:
index Com
0 1 Paris 03
1 2 Paris 17
2 3 Marseille 05
3 4 Abainville
4 5 Aast
5 6 Marseille 15
6 7 Lyon 04
Upvotes: 0
Reputation: 14949
use zfill
method to pad zeros.
df = df.convert_dtypes()
df.Com = df.Com.astype(str).str.zfill(2)
Upvotes: 0
Reputation: 18306
df.Com = df.Com.str.replace(r"\D(\d)$", r" 0\1")
You can see the regex demo. It looks at a non-digit and a single digit afterwards, all at the end of the string. Captures the single digit (in \1
) and pads it with a 0.
to get
>>> df
index Com
0 1 Paris 03
1 2 Paris 17
2 3 Marseille 05
3 4 Abainville
4 5 Aast
5 6 Marseille 15
6 7 Lyon 04
Upvotes: 1