0

At the moment I'm trying to write a dictionary to a file (in the same way the file is read). I thought using pandas was a good idea (since I also use it for reading of the same file), but that doesn't do what I want.

My data looks someting like this:

dict = {'x': np.array([1,2,3,4,5,etc.]), 'h': np.array([4,5,6,7,8,etc.])}

I want this data to be written to a file in the following format (since I retrieve it in this way as well):

x          h
1          4
2          5
3          6
4          7
5          8
etc.       etc.

I tried this, which works, but not in the way I want it:

a = pd.Series(dict)
a.to_csv(filename, sep='\t')

Any advice on how to do this (or is it easier to write it using just python?)

2
  • "I tried this, which works, but not in the way I want it:" What is happening instead? Commented Nov 21, 2014 at 11:14
  • @MrE I've just tried it, it writes a file with two lines, h [4 5 6 7 8] and x [1 2 3 4 5]. Commented Nov 21, 2014 at 11:15

1 Answer 1

1

Since you have multiple series of data, the right data structure for you in Pandas is the DataFrame. Having a look at the options for writing CSV files, I see that for your desired output, I also have to pass the argument index=False (otherwise it would write the row numbers in the first column).

import pandas as pd
d = {'x': np.array([1,2,3,4,5]), 'h': np.array([4,5,6,7,8])}

a = pd.DataFrame(d)
a.to_csv("testfile.txt", sep="\t", index=False)

This code produces the following text file:

h   x
4   1
5   2
6   3
7   4
8   5

PS: Don't create a variable named dict. It'll overwrite the type.

Sign up to request clarification or add additional context in comments.

Comments

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.