I have a multiline string (and not a text file) like this:
JavaScript
x
11
11
1
x = '''
2
Index Value Max Min State
3
0 10 nan nan nan
4
1 20 nan nan nan
5
2 15 nan nan nan
6
3 25 20 10 1
7
4 15 25 15 2
8
5 10 25 15 4
9
6 15 20 10 3
10
'''
11
The column white spaces are unequal.
I want to replace the whitespace
with a comma
, but keep the end-of-line
.
So the result would look like this:
JavaScript
1
9
1
Index,Value,Max,Min,State
2
0,10,nan,nan,nan
3
1,20,nan,nan,nan
4
2,15,nan,nan,nan
5
3,25,20,10,1
6
4,15,25,15,2
7
5,10,25,15,4
8
6,15,20,10,3
9
…or alternatively as a pandas
dataframe.
what i have tried
- I can use
replace('')
with different spaces, but need to count the white spaces - I can use the
re
module (from here re.sub question ), but it converts the whole string to 1 line, where as i need to keep multiple lines (end-of-line).
Advertisement
Answer
Try with StringIO
JavaScript
1
26
26
1
from io import StringIO
2
import pandas as pd
3
4
5
x = '''
6
Index Value Max Min State
7
0 10 nan nan nan
8
1 20 nan nan nan
9
2 15 nan nan nan
10
3 25 20 10 1
11
4 15 25 15 2
12
5 10 25 15 4
13
6 15 20 10 3
14
'''
15
16
df = pd.read_csv(StringIO(x), sep='ss+', engine='python')
17
18
Index Value Max Min State
19
0 0 10 NaN NaN NaN
20
1 1 20 NaN NaN NaN
21
2 2 15 NaN NaN NaN
22
3 3 25 20.0 10.0 1.0
23
4 4 15 25.0 15.0 2.0
24
5 5 10 25.0 15.0 4.0
25
6 6 15 20.0 10.0 3.0
26