Python:序列编码为字符串

Python: Series encoded as a string

我的问题很简单。

我有一个编码为字符串的系列(在我的代码中为'series_as_string'),我想将其作为一系列浮点数('series_as_series')。

我已经尝试了一些选项:使用 pd.Series 阅读系列,保存并使用 pd.read_csv() 阅读,...我想解析字符串并将其编码为列表,但我没有找到有效的方法...

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])

非常感谢您的帮助!

你可以read_csv使用 io 模块

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)

输出:

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

如果你特别想要系列:

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