简体   繁体   中英

Python: Series encoded as a string

my problem is quite simple.

I have a series that is encoded as a string ('series_as_string' in my code) and I want to have it as a series of floats ('series_as_series').

I have already tried some options: read the Series with pd.Series, save it and read it with pd.read_csv(), ... I wanted to parse the string and encoded it as a list but I didn't find an efficient way to do it...

series_as_string = """0      0.7070
1      1.4332
2      2.1882
3      2.9695
4      3.7748

Length: 5, dtype: float64"""

series_as_series = pd.Series([0.7070, 1.4332, 2.1882, 2.9695, 3.7748])

Thanks a lot for your help !

you can read_csv with io module

import io
series_as_string = """0      0.7070
1      1.4332
2      2.1882
3      2.9695
4      3.7748

Length: 5, dtype: float64"""
fixed_string = '\n'.join(series_as_string.split('\n')[:-2])
df = pd.read_csv(io.StringIO(fixed_string),sep='\s+',header=None)
print(df)

Output:

    0   1
0   0   0.7070
1   1   1.4332
2   2   2.1882
3   3   2.9695
4   4   3.7748

if you want specifically Series:

sr = df.iloc[:,1]
sr = 
0    0.7070
1    1.4332
2    2.1882
3    2.9695
4    3.7748
Name: 1, dtype: float64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM