使用Python更改csv的结构以适用于Turicreate推荐系统

2024-05-08 04:02:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问问我的问题。我想用python创建一个推荐系统。我已经创建了一个潜在函数矩阵,并将其存储在csv中,其中包含如下数据:

index    1        2        3       ...      89
1        a        b        c       ...      z
2        d        e        f       ...      y
...
30       g        h        i       ...      x

对于推荐系统,我使用了turicreate库,但是turicreate只能接受如下csv结构:

col   index    value
1       1       a
1       2       d
...
89      30      x 

有人能帮我解决这个问题吗?或者有人能为这个问题提供其他建议吗?因为我是python3的初学者。谢谢


Tags: csv数据函数indexvalue系统矩阵col
1条回答
网友
1楼 · 发布于 2024-05-08 04:02:53

如果你不介意使用熊猫:^{}

df = pd.read_csv(<filename>, <csv_options>)
df_stacked = df.stack()
df_stacked .to_csv(<out_file>, <csv_options>)

如果您想在纯python中执行此操作,可以使用以下方法:

import csv
with open(<in_filename>) as in_file, open(<out_filename>, "w") as out_file:
    csv_reader = csv.DictReader(in_file, delimiter=' ', skipinitialspace=True) # or appropriate csv parameters
    csv_writer = csv.writer(out_file)
    csv_writer.writerow(["col", "index", "value"])
    for row in csv_reader:
        col = row.pop("index")
        csv_writer.writerows((col, idx, value) for idx, value in row.items())

相关问题 更多 >