I have a dataframe that instead of .
it has ,
and separators of numbers are also comma,
I need to replace only odd comma to dot.
The dataframe is very big but as an example,
I have this:
JavaScript
x
6
1
+---+-----------------+
2
|id |values |
3
+---+-----------------+
4
| 1 | 12,3,10,4,11,5 |
5
+---+-----------------+
6
I want this df:
JavaScript
1
6
1
+---+-----------------+
2
|id |values |
3
+---+-----------------+
4
| 1 | 12.3,10.4,11.5 |
5
+---+-----------------+
6
Advertisement
Answer
You can split on all commas ,
and later you can use for
-loop:
- with
range(0, len(splitted_data), 2)
to create pairs[0:2]
,[2:4]
, …,[n:n+2]
and join them to strings with dots:
JavaScript
1
20
20
1
data = '12,3,10,4,11,5'
2
3
splitted_data = data.split(',')
4
5
new_values = []
6
7
for n in range(0, len(splitted_data), 2):
8
pair = splitted_data[n:n+2]
9
text = '.'.join(pair)
10
11
new_values.append(text)
12
13
print(text)
14
15
# -- after loop ---
16
17
data = ','.join(new_values)
18
19
print(data)
20
- with
iter()
withzip()
to create pairs and join them to strings with dots:
JavaScript
1
21
21
1
data = '12,3,10,4,11,5'
2
3
splitted_data = data.split(',')
4
5
iterator = iter(splitted_data)
6
7
new_values = []
8
9
for pair in zip(iterator, iterator):
10
text = '.'.join(pair)
11
12
new_values.append(text)
13
14
print(text)
15
16
# -- after loop ---
17
18
data = ','.join(new_values)
19
20
print(data)
21
Result:
JavaScript
1
5
1
12.3
2
10.4
3
11.5
4
12.3,10.4,11.5
5
EDIT:
You may also use regex
for this
JavaScript
1
6
1
import re
2
3
data = '12,3,10,4,11,5'
4
5
print(re.sub('(d+),(d+)', '\1.\2', data))
6
Result:
JavaScript
1
2
1
12.3,10.4,11.5
2