【问题标题】:Change structure of csv in python for turicreate recommender system为 turicreate 推荐系统更改 python 中的 csv 结构
【发布时间】:2019-05-12 00:12:40
【问题描述】:

我想问一下我的问题。我想在 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 

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

【问题讨论】:

标签: python csv recommendation-engine recommender-systems turi-create


【解决方案1】:

如果您不介意使用 pandas:pandas.DataFrame.stack

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

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多