gpt4 book ai didi

python - 将发往 pandas.series 的数据转换为干净的数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:15 24 4
gpt4 key购买 nike

我需要创建三个pandas.Series (x,y,z)。此数据的格式有多种。有些由 \n 分隔和; ,有些仅使用空格分隔。我想要一种通用的方法来将这些数据提取到列表中。数据看起来像这样:

x is "\n -10.03 -7.02 -0.05 9.96 20 40"
y is "\n 0.70;\n 0.79;\n 0.90;\n 1.00"
z is "\n 100.00 100.00 100.00 100.00 100.00 100.00;\.." (24 times)

最佳答案

这可以使用正则表达式和列表理解来完成:

代码:

import re
split_pattern = re.compile(r'[\n \t;]+')

x = '\n -10.03 -7.02 -0.05 9.96 20 40'
y = '\n 0.70;\n 0.79;\n 0.90;\n 1.00'
z = '\n 100.00 100.00 100.00 100.00 100.00 100.00;'

for data in (x, y, z):
data_list = [float(d) for d in split_pattern.split(data) if d != ""]
print(data_list)

结果:

[-10.03, -7.02, -0.05, 9.96, 20.0, 40.0]
[0.7, 0.79, 0.9, 1.0]
[100.0, 100.0, 100.0, 100.0, 100.0, 100.0]

关于python - 将发往 pandas.series 的数据转换为干净的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42571173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com