gpt4 book ai didi

python - 从 pandas 中修改后的 csv 加载数据集

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:44 25 4
gpt4 key购买 nike

我有一个数据文件,其中存储的数据如下:

key1:0.2164  key2:0.321  key3:0.1231
key1:0.3216 key2:0.149 key3:0.7894
...

所以基本上,列名被写成某种键。行由文本文件中的新行分隔。没有昏迷。我想把它变成一个合适的数据框,其中 columns=[key1,key2,key3]

显然使用 pd.read_csv(...,sep=':') 是不够的,因为我最终在每个单元格中得到了像 key1:0.1231 这样的值,它应该是 0.1231

我不确定我是否应该使用特殊的正则表达式作为分隔符,或者我是否应该使用另一种方法来加载文件(因为它不是真正的 .csv)

最佳答案

在数据进入数据帧之前执行操作通常效率更高。下面是一个使用 csv 模块的例子:

import pandas as pd
import csv
from io import StringIO

x = StringIO("""key1:0.2164 key2:0.321 key3:0.1231
key1:0.3216 key2:0.149 key3:0.7894 """)

# replace x with 'file.csv'
with x as fin:
reader = csv.reader(fin, delimiter=' ')
df = pd.DataFrame([dict(i.split(':') for i in filter(None, row)) for row in reader],
dtype=float)

结果:

     key1   key2    key3
0 0.2164 0.321 0.1231
1 0.3216 0.149 0.7894

此逻辑有效是因为 pd.DataFrame 构造函数接受字典列表作为输入。

关于python - 从 pandas 中修改后的 csv 加载数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52500368/

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