4

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?

2
  • IIUC you can transpose the df: df=pd.DataFrame(data=Com).T prior to writing out to csv Commented Dec 7, 2016 at 15:17
  • @EdChum oh wow, yeah that works perfectly. Thanks alot Commented Dec 7, 2016 at 15:20

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a good reason to prefer df.T over df.transpose()? I imagine they are exactly the same under the hood. To me .transpose() seems more self-documenting, but perhaps that's not idiomatic pandas.
@StevenRumbalski it's a numpy convention, if you're coming from numpy then it should be familiar to the reader, plus if you hate typing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.