jef jef - 1 year ago 90
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='')

But how do I also add a column label?

Answer Source
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')


    x   y   z
a   1   3   4
b   4   3   2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download