Change structure of csv in python for turicreate recommender system

122 Views Asked by At

I want to ask about my problem. I want to create a recommender system in python. I already create a latent function matrix and stored it in csv that contain data like this:

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

For the recommender system, I used turicreate library but turicreate can only accept if the structure of csv like this:

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

Can someone help me for this problem? or can someone give another suggestions for this problem? Because I am a beginner in python 3. Thanks

1

There are 1 best solutions below

0
On

if you don't mind using pandas: pandas.DataFrame.stack

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

If you want to do it in pure python, something like this can work:

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