Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas writing in csv file as columns not rows-Python

This is my code:

import os

file=[]

directory ='/Users/xxxx/Documents/sample/'
for i in os.listdir(directory):
   file.append(i)


Com = list(file)
df=pd.DataFrame(data=Com)
df.to_csv('com.csv', index=False, header=True)

print('done')

at the moment I am getting all the values for i in one column as a row header. Does anyone know how to make each i value in one row as a column header?

like image 480
reuben Avatar asked Nov 15 '25 05:11

reuben


1 Answers

You need to transpose the df first using .T prior to writing out to csv:

In [44]:
l = list('abc')
df = pd.DataFrame(l)
df

Out[44]:
   0
0  a
1  b
2  c

compare with:

In [45]:
df = pd.DataFrame(l).T
df

Out[45]:
   0  1  2
0  a  b  c
like image 155
EdChum Avatar answered Nov 17 '25 22:11

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!