How do you save multiple lists into a csv file with a title for each list?

时间:2018-04-18 17:49:12

标签: python pandas matrix

I have multiple matrices (let' say there are 30 of them) that need to be stored into a single csv file. Since there are so many of them, I want each matrix to have number before them. For example, 0 or Matrix-0 for matrix 0, 1 for matrix 1, and so on.

I have written the following code. Both temp1 and temp2 are matrices (list), which I append to a dataframe. But I have a problem storing them all without mixing all the matrices together (they are all different matrices but of the same size). I need to tell which matrix comes from which iteration, etc.

def my_function(df):
..............................
..............................
    conf_matrix = metrics.confusion_matrix(y_test,y_pred_class)
    print(conf_matrix)
    df_conf_matrix = pd.DataFrame(conf_matrix)

    return(df_conf_matrix)

df1 = pd.DataFrame()
df2 = pd.DataFrame()

for i in range(0,30):
    print("**ITERATION-%d**"%i)
    temp1, temp2 = my_function(my_df)
    df1 = df1.append(temp1)
    df2 = df2.append(temp2)

df1.to_csv('file_name1')
df2.to_csv('file_name2')

1 个答案:

答案 0 :(得分:1)

我会添加一个索引列,告诉该行来自哪个迭代。然后,您可以按该列进行排序。我假设你的函数返回2个数据帧。

df1 = pd.DataFrame()
df2 = pd.DataFrame()

for i in range(0,30):
    print("**ITERATION-%d**"%i)
    temp1, temp2 = my_function(df1)
    temp1['iteration'] = 'iteration-{}'.format(i)
    temp2['iteration'] = 'iteration-{}'.format(i)
    df1 = df1.append(temp1)
    df2 = df2.append(temp2)

df1.to_csv('file_name1.csv')
df2.to_csv('file_name2.csv')