jef jef - 2 months ago 9
Python Question

Insert row and col label when dumping matrix data to text file in python

I want to insert labels to col and row. like below.

x y z
a 1 3 4
b 4 3 2


Actually I could do to add header like below.

row_label = ["a", "b"]
col_label = ["x", "y", "z"]
data = np.array([[1,3,4], [4,3,2]])
numpy.savetxt("out.csv", data, header=",".join(["x", "y", "z"]), delimiter=",", fmt="%.0f", comments='')
>>x,y,z
>>1,3,4
>>4,3,2


But how do I also add a column label?

Answer
import numpy as np
import pandas as pd
row_label = ["a", "b"]
col_label = ["x", "y", "z"]
data = np.array([[1,3,4], [4,3,2]])
df = pd.DataFrame(data, index=row_label, columns=col_label)
df.to_csv(r'temp.csv', sep='\t')

temp.csv

    x   y   z
a   1   3   4
b   4   3   2