jef - 1 year ago 51

Python Question

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 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')
```

temp.csv

```
x y z
a 1 3 4
b 4 3 2
```